Module 6 · Pointers and Memory — topic 5 of 5
Memory Management Fundamentals
How a C program's memory is organised — text, data, BSS, heap and stack — and the ownership rules, tools and habits that prevent leaks, overflows and dangling pointers.
Learning objectives
- Map each kind of variable to its memory segment
- Apply ownership rules to decide who frees memory
- Use sanitizers and Valgrind to find memory errors
Definition
Memory management is the discipline of acquiring, using and releasing memory correctly. A C process's address space is typically divided into the text (code), initialised data, BSS (zero-initialised data), heap (dynamic allocations) and stack (automatic variables and call frames) segments.
Introduction
When your program runs, the operating system gives it an address space divided into regions. Code lives in one place, globals in another, local variables on the stack, and malloc'd memory on the heap. Knowing which region a value lives in tells you how long it lives and who must clean it up.
Most serious C bugs are memory bugs: buffer overflows, use-after-free, double free, leaks and uninitialised reads. They are hard to see in testing because the program often keeps running. Good habits and the right tools make them visible.
Why it matters
Operating systems, computer architecture and compiler courses all assume you understand process memory layout.
Industry C code (embedded, kernels, databases) is reviewed specifically for memory safety; showing you can reason about ownership is a strong signal in interviews.
Detailed explanation
Text: the compiled machine code, usually read-only. String literals often live in a read-only data area nearby.
Data: globals and statics with non-zero initialisers. BSS: globals and statics without initialisers (zeroed at start-up).
Heap: grows as malloc requests memory; managed by the allocator. Stack: one frame per active function call holding parameters, locals and the return address; grows and shrinks automatically.
Ownership: for every allocation, decide which function or structure *owns* it and is responsible for freeing it. Document transfers: “returns a newly allocated string; the caller must free it.”
Tools: compile tests with -fsanitize=address,undefined -g (GCC/Clang) to detect overflows, use-after-free and undefined behaviour at run time. On Linux, valgrind --leak-check=full ./prog reports leaks.
Syntax
- Compile with
gcc -g -fsanitize=address,undefined prog.cwhile testing. - Release resources in reverse order of acquisition.
- A single cleanup section per function keeps frees in one place.
Code examples
Where variables live
3 0 7 11
Ownership documented and honoured
KENHOLT
More examples
Cleanup on every path
b[last] = 8 status 0 second allocation failed status -1
Step-by-step explanation
- Both pointers start as
NULL, so the cleanup code is safe no matter where a failure happens. - Each failure jumps forward to
cleanupinstead of returning immediately and leakinga. fail_secondsimulates an allocation failure so the error path can be tested.- At
cleanup, resources are freed in reverse order;free(NULL)does nothing. - A single
return statuskeeps one exit point.
Expected output
Running “Cleanup on every path” prints exactly:
Practical applications
- Long-running servers are monitored for memory growth caused by leaks.
- Browsers and operating systems run fuzzers with AddressSanitizer to find memory bugs.
- Embedded systems often forbid
mallocafter start-up to make memory use predictable.
Best practices
- Decide and document ownership for every pointer that refers to heap memory.
- Test with sanitizers turned on; fix every report.
- Prefer fixed-size or stack storage when sizes are small and known.
Common mistakes
Leaking on an early return
Avoid
Prefer
Every exit path must release what was acquired. A cleanup label makes this systematic.
Freeing a stack address
Avoid
Prefer
Only pointers returned by malloc, calloc or realloc may be freed.
Important notes
- Stack and heap growth directions and segment placement vary by OS; the conceptual layout is what matters.
- Address space layout randomisation (ASLR) means addresses printed with
%pchange on every run.
Key takeaways
- Text, data, BSS, heap and stack hold different kinds of objects.
- Every allocation needs a clear owner who frees it once.
- Sanitizers and Valgrind find memory bugs that tests miss.
Try it yourself
- 1Write a program with a deliberate leak, run it with
-fsanitize=address(or Valgrind) and read the report. - 2Refactor a function with three
malloccalls to use a single cleanup label.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
4 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhere are local (automatic) variables stored?
- BeginnerWhat is a memory leak?
- AdvancedIn which segment is the variable `buf` itself stored in `void f(void) { static char buf[1024]; }`?