icp/oer/courses/c-basics/sections/24-dynamic-memory/01-introduction/content.html

21 lines
1.8 KiB
HTML

<p>
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.
</p>
<p>
The <b>stack handles</b> basically anything concerning your <b>subroutines</b>. It provides a simple way to change to a different function and return while keeping all the local data accessible.
</p>
<p>
Earlier we told you, that the stack only can <b>pop and push</b>. This is normally true, but to achieve the calling and returning of the function, we need two more instructions. The <b>call</b> instruction and the <b>ret</b> instruction. This is all done with only two pointers into your stack memory.
</p>
<p>
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.
</p>
<p>
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.
</p>
<p>
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.
</p>