Stack Memory

I am sure a lot of you have used stackoverflow.com right? Stack overflows is one of the hardest problems to catch and diagnose, and thus no wonder someone invented this creative website URL.

Stack memory is required for the following:

  1. Local Variables: Stored in the stack frame and automatically cleaned up when the function exits.
  2. Function Calls: When a function is called, a stack frame is created and pushed onto the stack.
  3. Function Returns: When a function completes, its stack frame is popped off the stack.

Fundamentally, a single core CPU contains a "Stack Pointer" which is a hardware register keeping track of memory. When a compiler generates code for a local variable, the stack pointer is typically decremented to make space for that variable.

void example_function() {
  int local_variable;
}

// Assembly:
example_function:
    push {lr}                   // Save the link register (return address)
    sub sp, sp, #4              // Decrement the stack pointer by 4 bytes to allocate space for localVariable
    ...
    add sp, sp, #4              // Clean up the stack by incrementing the stack pointer
    pop {pc}                    // Restore the link register and return from the function

 

Back to top