
(The same applies to longjmp if it moved to a point before the call to alloca happened.) If however, the data needs to be kept in some form, then it must be copied from the stack to the heap before the function exits. Another feature is that memory on the stack is automatically, and very efficiently, reclaimed when the function exits, which can be convenient for the programmer if the data is no longer required. stack-based memory allocation.īecause the data is added and removed in a last-in-first-out manner, stack-based memory allocation is very simple and typically much faster than heap-based memory allocation (also known as dynamic memory allocation) typically allocated via malloc. If a region of memory lies on the thread's stack, that memory is said to have been allocated on the stack, i.e. Programmers may further choose to explicitly use the stack to store local data of variable length.

The stack is often used to store variables of fixed length local to the currently active functions. At a minimum, a thread's stack is used to store the location of a return address provided by the caller in order to allow return statements to return to the correct location.

When a function executes, it may add some of its local state data to the top of the stack when the function exits it is responsible for removing that data from the stack. In most modern computer systems, each thread has a reserved region of memory referred to as its stack. Stacks in computing architectures are regions of memory where data is added or removed in a last-in-first-out (LIFO) manner. Each procedure called in the program stores procedure return information (in yellow) and local data (in other colors) by pushing them onto the stack. A push operation decrements the pointer and copies the data to the stack a pop operation copies data from the stack and then increments the pointer. The stack pointer points to the current topmost datum on the stack. This stack grows downward from its origin. A typical stack, storing local data and call information for nested procedure calls (not necessarily nested procedures).
