You already learned a bit about the stack. Now it is time to take deeper look at how the stack works and what it is used for.

The stack handles basically anything concerning your subroutines. It provides a simple way to change to a different function and return while keeping all the local data accessible.

Earlier we told you, that the stack only can pop and push. This is normally true, but to achieve the calling and returning of the function, we need two more instructions. The call instruction and the ret instruction. This is all done with only two pointers into your stack memory.

We need to know the top of the stack. This is handled with the stack pointer. And we need to know the position of the old stack pointer, the one before we called a subroutine. That is the base pointer. Together they form the current stack frame.

So how does calling a function work? This can vary from architecture to architecture, but there are lots of similarities. You first have to save certain registers. There are conventions for each register, if the caller or the callee has to save them. Then all the arguments for the subroutine get pushed followed by the return address. Finally the old base pointer gets pushed on the stack and the new one points to the stack pointer. Now the stack is prepared for the subroutine.

The stack is then used to hold all your local data or to call more functions. To return you simply move the stack pointer to the base pointer and then pop the old base pointer. Then you call ret, which just changes the instruction pointer to the return address. Last but not least you have to restore the registers. If the function has a return value, you have to place it in the designated return register. On x86 platforms it is the eax register.