Stack used in the Process memory

Stack grows from high to low

  • for simplicity consider memory address are in decimal with 4 digits
  • Stack starts with high value memory address “9999”
  • a new variable is added in the stack then the stack will grow to low memory address, i.e. the stack will point to 9995 (4 bytes for memory)

The main benefit of stack is that the data stored is sequential

  • So when CPU is accessing the data from the stack, it can also access some extra data in the same access cycle and can store it in the L cache. So next time, CPU will directly read from the L cache and a memory access call will be saved.

Below is the stack for nested function calls, main > func1

bp	1024   int a            main
	1020   int b
	1018
sp1	1014  ------------------func1
	1010  bp of main
	1006  pc of main (main's return address)
	1002  int x
	0998
sp2	0994
  • bp “base pointer”
  • sp1 start pointer when just main was present
  • sp2 current start pointer with func1 in execution

The CPU will have these stored in registers

  • bp - base pointer of current executing function

  • sp - start pointer of stack

  • lr - link register ( link to previous main’s return address)

  • pc - program counter of code of current executing function

  • When a new variable is created, the stack stores it and increments the sp

  • when the function is done executing, then the data of that func from stack is not removed, rather we just update the sp to current bp - 1

    • Here the bp of main will be lost, so we would need to save it to the stack of current function.
    • Also, need to save the pc of main to know the return address when the func is done executing