Stack vs Heap
The stack holds local variables that appear when a function is entered and vanish when it returns. The heap holds blocks you request explicitly, which stay alive until you free them, no matter which function does the freeing.
Detailed Explanation
Start with the honest caveat: the C standard never says the words "stack" or "heap". It talks about storage duration. A local variable has automatic storage duration, meaning its lifetime ends when the enclosing block ends. Memory from malloc has allocated storage duration, meaning its lifetime ends when you call free. "Stack" and "heap" are the names for how real implementations provide those two durations, and everyone uses them, so learn both vocabularies.
The stack is a single region that grows and shrinks at one end. Calling a function pushes a frame holding its parameters, its locals, and the return address. Returning pops the whole frame in one instruction that adjusts a register. That is why stack allocation is close to free: the cost is adding a constant to the stack pointer, and the memory is almost certainly already in cache because the same addresses were used by the previous call.
The heap is a general-purpose pool managed by library code. malloc searches its bookkeeping for a block of the right size, splits or extends as needed, records the size, and hands back a pointer. That search is bounded but real, and it is the reason a tight loop doing a million tiny malloc/free pairs is measurably slower than a loop using a local array.
| Stack | Heap | |
|---|---|---|
| Allocation cost | one register adjustment | allocator bookkeeping, sometimes a syscall |
| Size limit | small and fixed per thread | limited by address space and RAM |
| Lifetime | until the block exits | until you call free |
| Fragmentation | none, it is strictly LIFO | yes, long-lived mixed-size blocks scatter free space |
| Who cleans up | the compiler, automatically | you, explicitly, exactly once |
| Thread behaviour | each thread has its own stack | one shared heap, allocator is thread-safe but contended |
| Size known at | compile time (except VLAs) | run time |
The limit matters more than beginners expect. On typical Linux the main thread gets about 8 MB of stack; a thread created with pthread_create usually gets 8 MB too but this is configurable and often reduced to 512 KB or less in embedded and server settings. Declaring double buf[1000000] as a local asks for 8 MB in one go and will likely blow the stack. Running off the end of the stack is stack overflow, and it is undefined behavior. On mainstream desktop systems a guard page turns it into a prompt segmentation fault, which is lucky; on a microcontroller with no memory protection it silently corrupts whatever sits next to the stack.
The other classic bug is returning the address of a local. Once the function returns, the frame is gone. The pointer still holds a numeric address, and that address still names real memory, so reading through it often appears to work for a while. That is exactly what makes it dangerous: it is a dangling pointer, and using it is undefined behavior. C cannot return a bare array by value, so the alternatives are to have the caller pass in a buffer, to make the object static with the thread-safety cost that implies, or to malloc it and document who frees it.
How to decide? Default to the stack. It is faster, it cannot leak, and it needs no cleanup path. Reach for the heap when the size is only known at run time, when the object must outlive the function that creates it, when the object is large (say, more than a few kilobytes), or when you are building a structure that grows, such as a linked list or a dynamic array.
Code Examples
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* BROKEN: `local` lives in this function's frame. The frame is reclaimed on
return, so the returned pointer is dangling. This compiles, usually prints
something plausible, and is undefined behavior. */
static char *broken_greeting(void)
{
char local[32];
strcpy(local, "hello");
return local; /* never do this */
}
/* Correct option A: the caller owns the storage, so no allocation happens here.
This is the usual C convention: pass a buffer and its size. */
static void greeting_into(char *out, size_t out_size)
{
snprintf(out, out_size, "hello"); /* snprintf always terminates out */
}
/* Correct option B: this function allocates, and the caller must free().
Returns NULL on allocation failure. */
static char *greeting_alloc(void)
{
size_t n = sizeof "hello"; /* includes the '\0' */
char *p = malloc(n);
if (p == NULL) {
return NULL; /* the failure path is not optional */
}
memcpy(p, "hello", n);
return p;
}
int main(void)
{
char stack_buf[32]; /* automatic storage: freed on return */
greeting_into(stack_buf, sizeof stack_buf);
printf("%s\n", stack_buf); /* prints: hello */
char *heap_buf = greeting_alloc(); /* allocated storage: outlives the call */
if (heap_buf == NULL) {
return EXIT_FAILURE;
}
printf("%s\n", heap_buf); /* prints: hello */
free(heap_buf); /* caller frees, exactly once */
(void)broken_greeting; /* referenced but deliberately not called */
return 0;
}#include <stdio.h>
#include <stdlib.h>
/* Deciding by size and lifetime. A 4 MB buffer is fine on the heap and a bad
idea on the stack, where the whole thread may only have 8 MB. */
int main(void)
{
size_t n = 1024u * 1024u; /* one million doubles */
/* double big[1024 * 1024]; would ask for ~8 MB of stack: likely overflow. */
double *big = malloc(n * sizeof *big); /* sizeof *big, so the type appears once */
if (big == NULL) {
fprintf(stderr, "out of memory\n");
return EXIT_FAILURE;
}
big[0] = 1.0;
big[n - 1] = 2.0;
printf("%.1f %.1f\n", big[0], big[n - 1]); /* prints: 1.0 2.0 */
free(big);
return 0;
}Common Gotchas
Returning the address of a local is undefined behavior
the frame is reclaimed on return, so the pointer dangles. It frequently appears to work, because nothing has overwritten those bytes yet, which is precisely why the bug survives testing and fails in production. Compilers warn about the direct case (`-Wreturn-local-addr`) but cannot catch it when the address is stored into an output parameter.
Stack space is far smaller than you think
roughly 8 MB for the main thread on Linux and often under 1 MB for spawned threads or embedded targets. Large local arrays and deep recursion both exhaust it, and overflow is undefined behavior rather than a guaranteed clean crash.
Neither "stack" nor "heap" is a C standard term
the standard defines automatic, allocated, static, and thread storage durations. Implementations are free to satisfy automatic storage in registers or anywhere else, which is how a local variable can have no address at all after optimization.
Heap allocation is not free, and heaps fragment
a workload of many small, differently sized, long-lived allocations can end up holding far more memory than the sum of the live blocks, because free space is scattered in pieces too small to reuse.