Skip to content
systemcoding.dev
Systems Programming

Stack vs Heap Memory in C Explained

See where C variables live: the stack for locals that vanish on return, the heap for data you free yourself. Learn the limits, costs and bugs of each.

6 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the C, GNU and Rust logos.

A beginner's first confusing C bug is often a function that returns a pointer to a local variable and prints garbage, and the second is a program that crashes the moment it declares a large array. Both come from the same fact: C has two main places to put data, the stack and the heap, and they follow different rules about how long data lives and how much of it fits. This post explains both with programs you can compile, shows how to see the difference by printing addresses, and gives a rule for choosing.

The examples use C17, GCC 14 and glibc 2.40 on 64-bit Linux 6.12. Addresses and stack limits are the Linux x86-64 defaults, and other systems differ in the numbers but not in the ideas.

The stack

The stack is a region of memory that the program uses for function calls. Each time a function is called, the machine reserves a block on the stack for that call, called a stack frame. It holds the function's local variables, its parameters and the address to return to. When the function returns, its frame is released by moving one register, the stack pointer, and everything in the frame is gone. Allocation is almost free, a single subtraction, and cleanup is automatic.

stack_basic.cc
#include <stdio.h>

int square(int n)
{
    int result = n * n;      /* lives in square's frame */
    return result;
}

int main(void)
{
    int value = 7;           /* lives in main's frame */
    printf("%d squared is %d\n", value, square(value));
    return 0;
}
Text
7 squared is 49

value exists from the moment main starts until it returns. result exists only while square runs. You never allocate or free either one, and that is the appeal of the stack.

The cost is that the stack has a fixed size, chosen when the process starts. On Linux the main thread gets 8 MiB by default, which ulimit -s prints in kibibytes (8192). A thread created with pthread_create() gets its own stack, 8 MiB by default under glibc as well, derived from the same limit. Stack memory is also last-in, first-out: the data of the most recently called function is the first to go, so nothing on the stack can outlive the call that made it.

Returning a pointer to a local

That last rule is the source of the classic bug:

dangling.cc
#include <stdio.h>

int *make_number(void)
{
    int n = 42;
    return &n;               /* wrong: n dies when the function returns */
}

int main(void)
{
    int *p = make_number();
    printf("%d\n", *p);      /* undefined behavior */
    return 0;
}

GCC warns about this with -Wall: function returns address of local variable [-Wreturn-local-addr]. Do not ignore it. The program above may print 42, because the old frame's bytes are still there until another call overwrites them, or print something else, or crash. Which one happens can change with the optimization level. The pointer is dangling: it names a place that no longer belongs to you.

Stack overflow

A function that declares a very large local array, or recurses without a stopping point, runs past the end of the stack and the program is killed with SIGSEGV:

overflow.cc
#include <stdio.h>

int depth(int n)
{
    char pad[1024];          /* makes each frame about a kilobyte */
    pad[0] = (char)n;
    return depth(n + 1) + pad[0];
}

int main(void)
{
    printf("%d\n", depth(0));
    return 0;
}
Text
Segmentation fault (core dumped)

With 8 MiB of stack and frames of a little over 1 KiB, the recursion dies after something under 8,000 calls. A guard page just below the stack makes the failure a clean fault instead of corruption of whatever lies beyond. The practical rule is to keep individual locals small. A buffer of a few hundred bytes is fine. A buffer of a megabyte on the stack is a bug waiting for one more level of recursion or a smaller thread stack.

The heap

The heap is the region from which malloc() hands out memory. Unlike the stack, a block of heap memory lives until you call free() on it, regardless of which function allocated it. Blocks can be any size, limited by available memory rather than by a fixed stack, and a function can create a block and return it to its caller.

heap_basic.cc
#include <stdio.h>
#include <stdlib.h>

int *make_number(void)
{
    int *n = malloc(sizeof *n);

    if (n != NULL) {
        *n = 42;
    }
    return n;                /* fine: the block outlives the function */
}

int main(void)
{
    int *p = make_number();

    if (p == NULL) {
        return 1;
    }
    printf("%d\n", *p);
    free(p);                 /* the caller releases it */
    return 0;
}
Text
42

This is the correct version of the earlier function. The block was created inside make_number() and is still valid after it returns, because malloc() does not tie its lifetime to any function. The price is that somebody must free it, exactly once, and the language does nothing to remind you. Forgetting is a leak, freeing twice is a crash or worse, and using the block after freeing it is undefined behavior. The guide on dynamic memory allocation in this series covers these in detail.

Heap allocation is also slower than a stack allocation. malloc() has to find a block of the right size, update bookkeeping, and in a multithreaded program may take a lock. A function that allocates and frees a tiny block on every call can spend more time in the allocator than in its real work.

See the difference in addresses

You can watch the two regions with a program that prints the address of a local, a heap block and a global, and the address of main's code.

where.cc
#include <stdio.h>
#include <stdlib.h>

int global_counter = 1;

int main(void)
{
    int local = 0;
    int *heap = malloc(sizeof *heap);

    printf("code   %p\n", (void *)main);
    printf("global %p\n", (void *)&global_counter);
    printf("heap   %p\n", (void *)heap);
    printf("stack  %p\n", (void *)&local);
    free(heap);
    return 0;
}

The addresses change on every run, because Linux randomizes the layout (address space layout randomization), so the values below are examples. What is stable is the pattern: code and globals sit low, the heap is above them, and the stack is far higher, near the top of the user address space.

Text
code   0x55d0c3a4f189
global 0x55d0c3a52010
heap   0x55d0c4e9b2a0
stack  0x7ffd4b3e6f1c

The stack address starts with 0x7ff, the high end of a 47-bit address space, while the others begin with 0x55. Reading /proc/self/maps shows the same regions labeled [heap] and [stack].

Choosing between them

Ask three questions about each piece of data.

QuestionIf yesIf no
Is the size known at compile time and small?StackHeap
Does it have to outlive the function that creates it?HeapStack
Does it need to be larger than a few kilobytes, or grow?HeapStack

Small, short-lived, fixed-size data belongs on the stack: loop counters, a 64-byte scratch buffer, a small struct. Data that crosses function boundaries, such as a parsed document or a list that grows, belongs on the heap. When the same value can be either, prefer the stack, because it cannot leak and costs nothing to release.

A middle path is often best. The caller owns the memory and passes a pointer in, so the callee fills it and nothing needs returning:

caller_owns.cc
#include <stdio.h>
#include <string.h>

void fill_greeting(char *out, size_t cap, const char *name)
{
    snprintf(out, cap, "hello, %s", name);
}

int main(void)
{
    char buf[64];            /* stack buffer, owned by main */

    fill_greeting(buf, sizeof buf, "ada");
    puts(buf);
    return 0;
}
Text
hello, ada

The function writes into memory the caller provided, and snprintf() guarantees it will not write past cap bytes. No allocation, no free, no dangling pointer. This is the pattern behind many standard functions such as strftime() and snprintf() themselves.

What is not either one

Two other kinds of storage complete the picture. Globals and static variables live for the whole program in a fixed area that is set up before main runs. String literals such as "hello" live in read-only memory, so writing to one is undefined behavior and usually a crash. A static local keeps its value between calls, which makes it handy and also a trap for code that must be thread-safe, since all callers share the one copy.

Taggedcbeginner
Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.