Section 4.11

Static, stack, and heap storage

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: 400+768=1168400 + 768 = 1168 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.

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.

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.

  1. 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.

  2. 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.

  3. 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.

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.

Using an object outside its lifetime is undefined behavior §4.12: the standard places no requirement on what the program then does.

Let thread tt have a stack of StS_t bytes and a deepest demand of DtD_t bytes, counting every automatic object that is live at the deepest point. The stacks do not overflow if Dt≤StD_t \le S_t for every thread tt. Moving an object of bb bytes from the stack to static storage lowers DtD_t by at most bb for each thread whose deepest path contains the object, and it adds bb 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].