Stack and Heap

From SwinBrain

The concepts of Stack and Heap are essential to software development. In order to understand these concepts you need to understand how the operating system manages the programs you execute.

Process

A process is an operating system abstraction used to manage the execution of a program.

The programs that we write are saved to the computer as inactive lists of instructions and global data. The execution of these instructions happens within a process. In order to execute the program, the operating system will create a process into which the program's instructions and global data are loaded. The process will consist of several sections including those shown in the following list.

  • An image of the program's instructions (machine code).
  • A stack to keep track of the running Functions and Procedures.
  • A heap to hold dynamic data allocations used within the program.
Figure 1: An illustration of a process.

Stack

The call stack is part of a Process, it contains the executing functions and procedures. When a Function, Procedure or Method is called, the callers details and return address are saved to the stack, and space is allocated for the called method's parameters and local variables. When the code returns, the old code's values are loaded back into the registers and execution continues from where the call occurred.

Figure 2: Illustration of the stack.
  • Each Function Call and Procedure Call creates a frame on the stack.
  • The stack is automatically allocated and freed.
  • The call stack is also known as the execution stack, control stack, function stack, or runtime stack, but in many cases it is shortened to just the stack.
  • References and Pointers to stack values should only be passed to called methods, functions, or procedures as these values are freed once the the current frame ends (returns).

The Heap

The heap is a part of the Process, its the location in memory at which the program can dynamically allocated memory.

Figure 3: Illustration of the Heap


The heap contains all of the dynamically allocated data for your program.

  • In Pascal this includes values allocated using new as well as dynamic arrays, which are allocated using setLength. Figure 3 shows an illustration of data allocated on the heap, using a linked list as an illustration. The two nodes at the top right are a result of a leak, as they can no longer be reached from the Stack.
  • In Objective C all objects allocated using alloc, and any use of low level memory allocation functions such as malloc, result in values that are assigned onto the Heap.
  • Java, C# , and Visual Basic allocate all objects created using the new keyword and all arrays onto the Heap.
  • Values on the heap are referenced via pointers.
  • All values on the heap must be freed to avoid memory leaks.
  • The Memory Management article presents the three main approaches to memory management.

[edit]Links: Topic Brains
Return to Swin Brain