Definition
Static, stack and heap storage are the three places where a C program commonly keeps data. Static storage holds global variables and variables declared static; it is reserved at build time and lasts for the whole run. Stack storage holds a function’s local variables until the call returns. Heap storage is requested while the program runs, with malloc, and lasts until the program releases it with free. The three differ in what ends the data’s life: the end of the run, the return of the call, or an explicit release.
The idea
A function needs a work area of 768 bytes for one decoding step. Declared as a local array §14.5, the area costs nothing to create and disappears when the function returns. But the function runs on a thread whose stack is 1024 bytes, and the thread already uses 400 bytes at the point of the call: bytes do not fit. Declared static, the area no longer touches the stack, but now one area serves every caller, so two threads that call the function at the same time write into the same bytes. Obtained with malloc, the area is private to the call again, but the request can fail. Each place solves one problem and brings another.
A workshop is a fair picture. Shelves built into the walls (static storage) are always there, and everyone in the shop uses the same shelves. Each worker’s bench (the stack) has a fixed size and is cleared when the job is done. A storage unit rented from outside (the heap) can be of any size and kept as long as needed, but the rental office can run out of units, and someone must remember to hand the unit back. The picture stops being accurate in one respect: in a program all three are carved out of the same RAM, so space given to one is space taken from the others.
How it works
The C standard does not use the words stack and heap. It describes storage duration, the rule for how long an object, a region of memory that holds a value, exists. C11, the 2011 edition of the standard, has four storage durations, whose exact rules are stated further below.
Static storage duration, for the whole run: variables declared outside every function, and variables declared with the keyword
staticinside a function.Thread storage duration, one object per thread for as long as the thread runs: variables declared
_Thread_local.Automatic storage duration, for one execution of a block, the part of the program between a pair of braces: ordinary local variables and function parameters.
Allocated storage duration, from a call of
malloc,calloc,reallocoraligned_allocuntil a call offreeorreallocreleases the object.
Common implementations put static objects in fixed areas laid out by the linker §12.4, the tool that joins the compiled pieces into one program; automatic objects in the stack frame of the call; and allocated objects in the heap. The standard requires only the lifetimes. The places are the implementation’s choice.
Each place has its own costs.
Static storage. The linker places these objects in fixed areas:
.datafor variables with a non-zero initial value, whose initial values are also stored in the program file and copied into RAM when the program starts (on a microcontroller §6.1, from flash memory §6.6);.bssfor variables that start at zero, which cost RAM only; and read-only areas forconstdata, which on a microcontroller usually stay in flash memory. The total is known when the program is linked, and the linker reports an error if it does not fit. There is exactly one copy, shared by every function and every thread that uses it, and it keeps its contents from one call to the next.Stack storage. A call reserves its frame by moving the stack pointer, the register that marks the current end of the stack, which takes one instruction. Each call, and therefore each thread, gets its own copy, so two threads that run the same function do not share its local variables. A local variable starts with whatever bytes the memory held before, unless the program initializes it, and it is gone after the return. The stack’s size is fixed when the thread is created. Exceeding it is a stack overflow §4.10, which nothing reports when the program is built unless a stack analysis is run.
Heap storage. The program asks the allocator, the library code that manages the heap, for a block of a size chosen while running. The request can fail, and
mallocthen returns a null pointer §4.26. The block lives until the program frees it, so its ownership §4.2 must be clear: one part of the program must be responsible for freeing it, exactly once. The free memory of the heap can also split into pieces too small to use, which is heap fragmentation §4.9, and each block costs a few extra bytes of the allocator’s records.
Scope and storage duration are different properties. Scope is the part of the source code in which a name can be used; storage duration is how long the object exists. A variable declared static inside a function has the scope of that function, so no other function can name it, but it has static storage duration, so it exists for the whole run and keeps its value from one call to the next.
A large work area can leave the stack in three common ways.
One static area. Declare the area
static. The stack shrinks by the area’s size, but the area is now shared. If two threads can run the function at the same time, they must take turns, for example by holding a mutex §9.5, a lock that only one thread can hold at a time, while they use the area. An interrupt handler §6.12 must not wait for a mutex, so a function that an interrupt handler also calls needs a separate area for the handler.One area per thread. Give each thread that runs the function its own static area, or declare the area
_Thread_local. Nothing is shared, but the memory is reserved once per thread, the same total as on the stacks.A heap block. Allocate the area when it is needed and free it afterwards, or allocate it once at start-up and keep it. Allocating at every call adds a failure path to the function. Allocating once at start-up moves the failure to start-up, where it is easier to handle.
Worked example
Two worker threads, A and B, both call a function decode that needs a 768-byte work area. Without the area, each thread’s deepest stack use is 400 bytes, and each thread has a 1024-byte stack.
Work area on the stack. Each thread needs bytes, which exceeds its 1024-byte stack by bytes. Enlarging both stacks to fit costs bytes in total.
One shared static area with a mutex. Each stack needs only 400 bytes. The total is bytes, which is bytes less than with the area on the stacks. The price is that A and B can no longer decode at the same time.
One static area per thread. The total is bytes, the same as with the area on the stacks. Nothing is saved. The gain is that the linker checks the bytes when the program is built, and neither stack holds a large frame.
A heap block for each call. The two stacks need bytes. The heap must be able to supply two 768-byte blocks, plus the allocator’s records, whenever A and B decode at the same time, and each request can fail. Between calls those bytes are free for other users of the heap.
Moving the area therefore saves memory only when one copy can serve several threads. Otherwise it moves the same bytes to a place where they are counted when the program is built (static storage) or obtained when needed (the heap).
A static area also keeps its contents after the call. If decode leaves a decrypted key in the shared area, the key stays in RAM until the next call overwrites it, and any code that can read the area can read the key. The function should clear the area before it releases the mutex.
Stated precisely
Clause 6.2.4 of C11 states the lifetimes.
An object with static storage duration exists, and keeps its last-stored value, throughout the execution of the program, and it is initialized once, before program startup. Without an explicit initial value it starts as zero, or as a null pointer if it is a pointer.
An object with thread storage duration exists throughout the execution of the thread for which it was created.
An object with automatic storage duration, other than a variable-length array, exists from entry into the block in which it is declared until execution of that block ends in any way. Without an initial value its value is indeterminate, meaning that it may be any value, until the program stores one.
An object with allocated storage duration exists from the allocation call until the matching call of
freeorrealloc.
Using an object outside its lifetime is undefined behavior §4.12: the standard places no requirement on what the program then does.
Let thread have a stack of bytes and a deepest demand of bytes, counting every automatic object that is live at the deepest point. The stacks do not overflow if for every thread . Moving an object of bytes from the stack to static storage lowers by at most for each thread whose deepest path contains the object, and it adds bytes to the static total once if the object is shared, or once per copy otherwise. The linker checks the static total. The stack demands need a stack analysis, and the heap needs a bound on the bytes of the blocks that can be live at the same time.
Limits and common mistakes
Static does not mean read-only or private. Any code that can reach a static variable can write it, and a static area shared by two threads that use it at the same time without a lock is a data race §9.3: two accesses to the same memory, at least one of them a write, with nothing ordering them. Only const asks for read-only storage.
A shared static area destroys reentrancy §9.27. A function is reentrant if a second call can safely start before an earlier call has finished, for example when an interrupt handler calls the function while a thread is inside it. A function that keeps its work in shared static storage is not reentrant.
Never return the address of a local variable. The variable’s lifetime ends at the return, and the returned address becomes a dangling pointer §4.1, one that points at memory no longer reserved for its object.
The stack cost is the compiled frame, not the source. The compiler can keep a local variable in a register, give two variables the same place in the frame, or add padding. Take frame sizes from the build that runs.
Safety-related code often forbids the heap. MISRA C, a widely used set of coding rules for safety-related C from the Motor Industry Software Reliability Association, forbids the allocation functions of the standard library (Rule 21.3 of its 2012 edition) [452]. Such programs use static storage, or fixed-size pools set up at start-up.
Initialized static data costs twice on a microcontroller. A variable in .data occupies flash memory for its initial value and RAM for the variable itself. A large table that never changes should be declared const, so that it can stay in flash memory only.
Questions answered
Why move a large scratch region off a small thread stack?
Move it to keep the thread’s stack within its fixed size. A local array adds its full size to every call path through the function that declares it, and on a small stack that can cause a stack overflow: the stack’s contents spill into neighboring memory, usually with no warning when the program is built. Moving the region to static storage (one fixed area that exists for the whole run) or to the heap (a block requested while the program runs) takes those bytes out of the stack’s demand.
Moving the region does not make its bytes free. One static area shared by several threads saves memory, because one copy replaces one copy per stack, but the threads must take turns, for example under a mutex (a lock only one thread can hold), and an interrupt handler cannot wait for such a lock. One area per thread saves nothing, but the linker checks that memory when the program is built. A heap block adds a request that can fail and must be released exactly once. A static area also keeps sensitive data after the call unless the function clears it. The move is worth making when the stack size is fixed or cannot be raised, when several threads would each need the extra bytes on their stacks, or when a check of the memory at build time is wanted; its cost is sharing, failure handling or lifetime management.
Related entries: Stack overflow (§4.10), Ownership (§4.2), Heap fragmentation (§4.9), Object lifetime (§4.1). Further reading: [78, 452].