keepcalculator

06 Numbers and Powers

C Heap vs Stack Memory: What the Language Guarantees

Card No. 06·77498 · Updated · Standard formula, shown below

C’s memory model is often taught as “stack for local variables, heap for dynamic allocation,” but the language standard itself is more careful. What C actually guarantees is that objects with automatic storage duration (typically on the stack) are created and destroyed when control enters and leaves a block, while objects with allocated storage duration (the heap) persist until you explicitly free them. Everything else—where exactly they live, how fast they are, how much you can use—is implementation-defined or determined by the hardware and operating system.

Background: Why the Stack and Heap Exist

The stack is a region of memory managed by the compiler and the CPU’s stack pointer. It works like a stack of plates: each function call pushes a frame onto the stack, and each return pops it off. This is why local variables are automatically destroyed when a function returns—the frame is simply discarded. The stack is fast because it’s just moving a pointer, and it has excellent cache locality because the most recently used data is nearby.

The heap is a more flexible but slower region. It is managed by the runtime (via malloc, realloc, free in C) and the operating system. The heap allows you to allocate memory at runtime, of any size, and keep it alive across function calls. But this flexibility comes with a cost: allocation and deallocation are more complex, and the heap is shared among all threads, so it requires synchronization.

The C standard (ISO/IEC 9899) does not use the terms “stack” or “heap.” Instead, it defines three storage durations:

  • Static: exists for the entire program.
  • Automatic: exists until the block where it is declared exits.
  • Allocated: exists until free is called.

Most implementations map automatic to the stack and allocated to the heap, but the standard doesn’t require it. A conforming implementation could put automatic variables in a register, or even in a heap-like structure, as long as the observable behavior is the same.

What the C Standard Actually Guarantees

The C standard guarantees the lifetime and visibility of objects, not their physical location. For automatic variables, it guarantees that memory is reserved when the block is entered and released when the block exits. For allocated objects, it guarantees that memory is reserved when malloc succeeds and released when free is called. It does not guarantee that the stack is used, nor does it guarantee that the heap is used.

What it does guarantee is the behavior of the program. If you access an automatic variable after its block has exited, the behavior is undefined—the compiler can do anything, including crashing, producing garbage, or even appearing to work. This is the key distinction: the standard doesn’t say “the stack frame is gone,” it says “the variable’s lifetime has ended, and using it is undefined.”

The standard also guarantees that malloc returns a pointer aligned for any type, and that the allocated memory is not initialized (unless you use calloc). It guarantees that free makes the pointer invalid, and that double-freeing is undefined behavior. These are the real guarantees—they are about correctness, not about performance or location.

How the Stack Works in Practice

In practice, on virtually every desktop, mobile, and embedded system, automatic variables are placed on the stack. The stack is a contiguous block of memory, usually a few megabytes (on Linux, the default stack size is 8 MB; on Windows, 1 MB). Each function call pushes a frame that contains the return address, saved registers, and local variables.

Because the stack is LIFO (last-in, first-out), allocation is just a subtraction from the stack pointer, and deallocation is an addition. This is why stack allocation is essentially free—it’s a single instruction. However, the stack size is fixed at program start, so if you allocate too much (e.g., a large array on the stack), you get a stack overflow, which usually crashes the program.

Another important detail: the stack is not thread-safe by default. Each thread has its own stack, which is why local variables are naturally thread-local. This is a huge advantage for concurrency—no locks are needed for stack data.

How the Heap Works in Practice

The heap is a more dynamic region. When you call malloc(n), the runtime finds a block of at least n bytes in a free list or by requesting more memory from the OS via sbrk or mmap. This process is much slower than stack allocation, often by an order of magnitude, because it involves searching for a suitable block, possibly splitting or coalescing blocks, and sometimes making a system call.

The heap is also shared among all threads, so the allocator must use locks or atomic operations to prevent corruption. This can cause contention in multi-threaded programs. However, the heap allows you to allocate memory of any size, and the memory stays alive until you free it, regardless of which function allocated it. This is essential for data structures like linked lists, trees, and dynamic arrays.

One common misconception is that heap memory is always slower than stack memory. In practice, the difference is mostly in allocation and deallocation, not in access time. Once you have a pointer to the heap, reading and writing is the same speed as stack memory. The real cost is the allocation overhead, and the fact that heap objects are scattered, which can hurt cache locality.

Choosing Between Stack and Heap

Choosing where to put your data is a trade-off between speed, lifetime, and size. Here are the general rules:

  • Use the stack when: the data is small (a few hundred bytes), the lifetime is within a single function call, and you want the fastest allocation possible.
  • Use the heap when: the data is large (megabytes), the lifetime must extend beyond the function that creates it, or the size is only known at runtime.
  • Use the stack for temporary buffers: if you need a small scratch array, stack allocation is fine and avoids the risk of forgetting to free.
  • Use the heap for data structures: linked lists, trees, hash tables, and dynamic arrays must use heap allocation because they grow and shrink.

A common pattern is to use the stack for the “skeleton” of a function and the heap for the “meat.” For example, a function that processes a file might read the file size, allocate a buffer on the heap, and use a stack variable to hold the pointer.

Common Problems: Stack Overflow and Memory Leaks

The two most common problems are stack overflow and memory leaks. Stack overflow occurs when you allocate too much memory on the stack, either by declaring a huge array or by recursing too deeply. For example, a recursive function that never terminates will eventually exhaust the stack and crash. The solution is to either increase the stack size (not always possible) or move the recursion to an explicit heap-allocated stack.

Memory leaks occur when you allocate memory on the heap but never free it. In a long-running program, this can gradually consume all available memory. The C standard does not provide garbage collection—you must call free for every malloc. Tools like Valgrind can help detect leaks, but the best approach is to be disciplined about ownership: decide who is responsible for freeing each allocation, and make sure it happens exactly once.

Another subtle problem is dangling pointers: a pointer to memory that has been freed. Using such a pointer is undefined behavior. This can happen if you free memory while another pointer still references it, or if you return a pointer to a stack variable from a function. The latter is a classic bug:

int* bad_function() {
    int x = 42;
    return &x;  // x is destroyed when the function returns
}

Comparison: Stack vs Heap in C

Here’s a quick comparison of the two:

  • Allocation speed: Stack is nearly free; heap is slower due to bookkeeping.
  • Deallocation: Stack is automatic; heap requires explicit free.
  • Size limits: Stack is usually a few MB; heap can be gigabytes (limited by RAM/swap).
  • Lifetime: Stack data dies when the function returns; heap data lives until freed.
  • Thread safety: Stack is per-thread; heap is shared and needs synchronization.
  • Fragmentation: Stack has none; heap can fragment over time.

In terms of performance, the stack is generally better for small, short-lived data. The heap is necessary for large or long-lived data, but you must manage it carefully.

Costs and Safety

The cost of using the heap is not just speed—it’s also the risk of bugs. Memory leaks, double frees, and use-after-free are all undefined behavior that can lead to security vulnerabilities. The C standard does not protect you from these; it assumes you know what you’re doing. This is why many modern C projects adopt coding standards like MISRA C, which restrict dynamic allocation in safety-critical systems.

On the other hand, the stack is not without risks. Stack overflow can be caused by unbounded recursion, which is hard to debug. Also, the stack is limited, so you cannot allocate large arrays on it. In embedded systems, the stack size is often configured at compile time, and exceeding it can corrupt memory silently.

For safety, follow these rules:

  • Never return a pointer to a local variable.
  • Always check the return value of malloc—it can return NULL.
  • Always free what you allocate, and set the pointer to NULL after freeing to avoid double frees.
  • Use calloc if you need zero-initialized memory.
  • Prefer stack allocation for small, fixed-size buffers to avoid heap fragmentation.

Alternatives and Modern Practice

In modern C, there are a few alternatives to manual heap management. The alloca function allocates memory on the stack dynamically, but it is non-standard and dangerous if the size is large. Some compilers support variable-length arrays (VLAs) in C99, but they are optional in C11 and can cause stack overflow if misused.

For safer heap management, some projects use arena allocators or object pools, which allocate a large block once and then sub-allocate from it. This reduces fragmentation and makes freeing easier—you just free the whole arena. Another approach is to use smart pointers in C++ or Rust, but in pure C, you must rely on discipline.

The key takeaway is that the stack and heap are not just memory regions—they are different models of object lifetime. Understanding what the C standard guarantees (lifetime, not location) helps you write correct, portable code that works on any implementation.

Frequently Asked Questions

Is stack memory faster than heap memory?

Yes, for allocation and deallocation. Stack allocation is just a pointer adjustment, while heap allocation involves searching for a free block and possibly locking. However, accessing the data itself is the same speed; the difference is in the allocation overhead.

Can I use the heap without calling free?

You can, but it’s a memory leak. In a short-lived program, the OS reclaims memory when the process exits, but in a long-running program, leaks accumulate and eventually exhaust memory. Always free what you allocate.

What happens if I allocate a huge array on the stack?

You get a stack overflow, which usually causes a segmentation fault and crashes the program. The stack size is fixed (typically 1–8 MB), so large arrays should go on the heap.

Is it possible to access heap memory after free?

Technically, the memory might still be there, but doing so is undefined behavior. The pointer is invalid, and the memory may be reused by another allocation. This is a common source of bugs and security vulnerabilities.

Does C guarantee that the stack is used for local variables?

No. The C standard only guarantees the lifetime of automatic variables, not their physical location. On all real-world systems, they are on the stack, but a conforming implementation could use a different mechanism.

Why is the heap shared among threads but the stack is not?

Because each thread has its own stack by design, which makes local variables thread-safe. The heap is a global resource, so the allocator must handle concurrent access with locks, which can be a performance bottleneck.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →