Skip to content

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.

Beginner 15 min read·Lesson 26 of 37 in C Programming

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.

BugSymptomPrevention
Leakmemory use grows over timefree on every path; ownership rules
Double freecrash in allocatorset pointer to NULL after free
Use after freecorrupted data, crashesnever keep pointers to freed blocks
Buffer overflowcorrupted neighbours, security holesbounded functions; check sizes
Uninitialised readrandom valuesinitialise; use calloc

Syntax

C
int global_init = 5; /* data segment */
int global_zero; /* BSS */
void f(void) {
int local = 1; /* stack */
static int count; /* BSS */
char *buf = malloc(64); /* pointer on stack, block on heap */
free(buf);
}
  • Compile with gcc -g -fsanitize=address,undefined prog.c while testing.
  • Release resources in reverse order of acquisition.
  • A single cleanup section per function keeps frees in one place.

Code examples

Where variables live

C
#include <stdio.h>
#include <stdlib.h>
int counter = 3; /* data */
int zeroed; /* BSS: starts at 0 */
int main(void) {
int local = 7; /* stack */
int *heap = malloc(sizeof *heap);
if (!heap) return 1;
*heap = 11;
printf("%d %d %d %d\n", counter, zeroed, local, *heap);
free(heap);
return 0;
}
Output
3 0 7 11

Ownership documented and honoured

C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Returns a new heap copy of s. The caller owns it and must free it. */
char *dup_string(const char *s) {
size_t n = strlen(s) + 1;
char *copy = malloc(n);
if (copy) memcpy(copy, s, n);
return copy;
}
int main(void) {
char *name = dup_string("KENHOLT");
if (!name) return 1;
printf("%s\n", name);
free(name); /* the owner frees */
return 0;
}
Output
KENHOLT

More examples

Cleanup on every path

C
#include <stdio.h>
#include <stdlib.h>
/* Allocates two buffers; if any step fails, frees what was allocated. */
int process(size_t n, int fail_second) {
int status = -1;
int *a = NULL, *b = NULL;
a = malloc(n * sizeof *a);
if (!a) goto cleanup;
b = fail_second ? NULL : malloc(n * sizeof *b);
if (!b) { printf("second allocation failed\n"); goto cleanup; }
for (size_t i = 0; i < n; i++) { a[i] = (int)i; b[i] = a[i] * 2; }
printf("b[last] = %d\n", b[n - 1]);
status = 0;
cleanup:
free(b); /* free(NULL) is safe */
free(a);
return status;
}
int main(void) {
printf("status %d\n", process(5, 0));
printf("status %d\n", process(5, 1));
return 0;
}
Output
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 cleanup instead of returning immediately and leaking a.
  • fail_second simulates 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 status keeps one exit point.

Expected output

Running “Cleanup on every path” prints exactly:

TextOutput
b[last] = 8
status 0
second allocation failed
status -1

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 malloc after 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

char *buf = malloc(100);
if (!read_ok) return -1; /* buf leaked */
free(buf);

Prefer

char *buf = malloc(100);
if (!read_ok) { free(buf); return -1; }
free(buf);

Every exit path must release what was acquired. A cleanup label makes this systematic.

Freeing a stack address

Avoid

int x = 5;
int *p = &x;
free(p);

Prefer

int *p = malloc(sizeof *p);
*p = 5;
free(p);

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 %p change 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

  1. 1
    Write a program with a deliberate leak, run it with -fsanitize=address (or Valgrind) and read the report.
  2. 2
    Refactor a function with three malloc calls 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]; }`?
Practise this topic