C Reference ยท Concepts and Tools
Stack vs. heap in C
Compare stack and heap memory in C: lifetimes, size limits, speed, returning data from functions, dangling pointers, and how to choose between them.
Every object in a C program has a storage duration that decides how long it lives. In practice that comes down to a choice between two places. Automatic objects (local variables and parameters) live on the stack and disappear when their function returns. Allocated objects, created with malloc and friends, live on the heap until you call free.
The stack is fast and tidy: allocation is a pointer adjustment and cleanup is automatic. The heap is flexible: blocks can be any size, chosen at run time, and can outlive the function that made them. The cost of that flexibility is that you must manage the lifetime yourself, and mistakes become leaks, double frees and dangling pointers.
Comparing the two
| Stack | Heap | |
|---|---|---|
| Created by | declaring a local variable | malloc, calloc, realloc, aligned_alloc |
| Freed by | returning from the function | free |
| Size | fixed when you write the code (VLAs excepted) | chosen at run time |
| Size limit | small (about 1 to 8 MB per thread) | most of available memory |
| Speed | very fast | slower: the allocator searches for space |
| Failure | crash on overflow, no error code | NULL return you can check |
| Lifetime | one function call | until freed |
| Initial contents | indeterminate | indeterminate (calloc: zero) |
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
The classic mistake: a pointer to a stack object
Read-only. This function returns the address of an array that no longer exists once the function returns. The compiler usually warns (-Wreturn-local-addr), and using the pointer is undefined behavior.
char *bad_name(void) { char name[16] = "temporary"; return name; /* WRONG: name dies at the closing brace */ }
Fixes: return a struct by value, allocate with malloc and document that the caller must free, or let the caller pass a buffer.
Choosing
- Use the stack by default. Small, fixed-size objects with a lifetime that matches the function belong there.
- Use the heap when the size is not known until run time, the object must outlive the function that creates it, the object is large (arrays of thousands of elements), or you build linked structures such as lists and trees.
- Use
staticstorage for tables that exist for the whole program or for buffers too large for the stack but with a fixed size. The cost is that they are not re-entrant or thread-safe unless you protect them.
Usage notes
- Stack overflow is silent until it crashes. Deep recursion or a large local array (
char buf[10000000];) can exceed the limit. Use iteration or the heap. - VLAs hide the same risk. A variable-length array lives on the stack and has no failure check; a bad size is undefined behavior. They are optional since C11. See VLA.
- Every
mallocneeds onefree. Missing it is a leak; doing it twice is a double free; using the block afterwards is use-after-free. See Memory errors. - Check
mallocforNULL. The stack has no such check, the heap does. - Allocation costs. A heap call may take tens to hundreds of nanoseconds and fragments memory over time. Reusing buffers, allocating in bulk or using an arena are common remedies.
- Threads. Each thread has its own stack; the heap is shared, and
mallocis thread-safe. - Do not write
freeon stack or static addresses. Only pointers returned by the allocation functions may be passed tofree.
Related
- Program memory layout
- malloc, realloc and free
- Storage duration
- Tutorial: Dynamic memory and Memory layout