Loading...

C essentialsPointers & Memory

Memory layout: stack, heap & static

10 min lesson

Next
  • A running C program uses several regions of memory: the stack, the heap, and the static/global area, plus the code area.
  • Knowing the layout matters because it explains where variables live, why locals disappear, and when you must free memory.
  • Think of memory as a building: the stack is a stack of trays at the entrance, the heap is a big storeroom, and the static area is a set of lockers reserved for the whole day.
  • The stack holds local variables and function call information; it grows and shrinks automatically as functions are called and return.
  • The heap is a pool of memory you request at runtime with malloc and release with free; it stays allocated until you free it.
  • The static/global area holds global variables and static locals, which live for the whole program.
  • The code area holds the compiled instructions and string literals; it is usually read-only.
  • The computer gives each function a stack frame on call and removes it on return; the heap grows on demand from the operating system.
  • The syntax is: locals are automatic (no keyword); heap memory comes from malloc; globals and statics are declared at file scope or with static.
  • A realistic use: a large buffer should go on the heap so it does not overflow the small stack, while small locals stay on the stack.
  • A surprising detail: a function returning a pointer to its local variable is a bug, because the stack frame disappears when the function returns.
  • The example program compares the addresses of a local, a static and a heap variable to show they live in different regions.
Keep in mind
  • Locals live on the stack and vanish when the function returns.
  • Heap memory lives until you free it; you are responsible for freeing.
  • Globals and statics live for the whole program.
  • Never return a pointer to a local variable.
  • Understanding memory layout makes you a safer programmer. Well done!
main.c
#include <stdio.h>
#include <stdlib.h>

// A global variable lives in the static area for the whole program
int globalCounter = 0;

int main(void) {
    // A local variable lives on the stack
    int localValue = 10;
    // A static local also lives in the static area
    static int staticValue = 20;
    // Heap memory comes from malloc and must be freed
    int *heapValue = malloc(sizeof(int));
    // Always check that malloc succeeded
    if (heapValue == NULL) {
        return 1;
    }
    // Store a value in the heap block
    *heapValue = 30;

    // Print addresses to see they are in different regions
    printf("local:  %p\n", (void *)&localValue);
    printf("static: %p\n", (void *)&staticValue);
    printf("global: %p\n", (void *)&globalCounter);
    printf("heap:   %p\n", (void *)heapValue);

    // Release the heap memory when done
    free(heapValue);

    return 0;
}

What happens: local: 0x7ffe5c3a1b2c static: 0x55a1f2c3d010 global: 0x55a1f2c3d014 heap: 0x55a1f3e4a2a0

Breaking it down

Global variable

int globalCounter = 0;

Lives in the static area for the entire program. Every function can see it if declared before use.

Local variable

int localValue = 10;

Lives on the stack inside main. It is created when main starts and removed when main returns.

Static local

static int staticValue = 20;

Lives in the static area, not the stack, so it keeps its value between calls if declared in a function.

Heap allocation

malloc(sizeof(int))

Asks the operating system for memory on the heap. It returns an address, or NULL if it fails.

Freeing

free(heapValue);

Returns the heap block to the system. Forgetting this leaks memory; using it after free is a bug.

Memory regions in a C program

RegionWhat lives thereLifetimeManaged by
StackLocals, function framesUntil function returnsCompiler
Heapmalloc'd blocksUntil freeProgrammer
StaticGlobals, static localsWhole programCompiler
CodeInstructions, literalsWhole programRead-only

A helpful analogy

Memory is like a building. The stack is a stack of trays at the entrance: quick to grab, but each tray goes away when you leave. The heap is a big storeroom: you can reserve space for as long as you need, but you must return the key (free). The static area is a set of lockers reserved for the whole day, and the code area is the printed instruction board on the wall.

Nesting rules

  • 1.Never return a pointer to a local variable; its stack frame disappears on return.
  • 2.Free every heap block exactly once, and set the pointer to NULL after free.
  • 3.Large buffers belong on the heap; the stack is small and can overflow.
  • 4.Global and static variables are zero-initialized, but locals are not.

Common mistakes

Returning a pointer to a local

Avoid

int *f(void) { int x = 5; return &x; }

Use instead

int *f(void) { int *p = malloc(sizeof *p); *p = 5; return p; }

The local x disappears when f returns, so the pointer points to dead memory. Use heap memory or a static variable instead.

Forgetting to free heap memory

Avoid

int *p = malloc(sizeof(int)); // no free

Use instead

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

Heap memory is not released automatically at the end of a function. Unfreed blocks leak until the program ends.

Putting a huge array on the stack

Avoid

int big[10000000]; // may crash

Use instead

int *big = malloc(10000000 * sizeof(int));

The stack is small, often 1 to 8 MB. Big arrays overflow it. Allocate large data on the heap.

Quick tips

  • •Print addresses with %p to see which region variables live in.
  • •Keep the stack small; move large data to the heap.
  • •Free heap memory on every path, including error paths.
  • •Try declaring a big local array to see the crash, then move it to the heap.
  • •Use valgrind or -fsanitize=address to detect leaks and use-after-free.
Previous
Next