C/C++ Stack Frame – Understanding Stack Frame of Function Call in C/C++

ccompilerstack

I am trying to understand how stack frames are built and which variables (params) are pushed to stack in what order? Some search results showed that the C/C++ compiler decides based on operations performed within a function. For example, if the function was supposed to just increment a passed-in int value by 1 (similar to ++ operator) and return it, it would put all the parameters of the function and local variables into registers.

I'm wondering which registers are used for returned or pass by value parameters. How are references returned? How does the compiler choose between eax, ebx,ecx and edx?

What do I need to know to understand how registers, stack and heap references are used, built and destroyed during function calls?

Best Answer

In addition to what Dirk said, an important use of stack frames is to save previous values of registers so that they can be restored after a function call. So, even on processors where registers are used for passing parameters, returning a value, and saving the return address, the values of those registers are saved on the stack before a function call so that they can be restored after the call. This allows one function to call another without overwriting its own parameters or forgetting its own return address.

So, calling a function B from function A on a typical "generic" system might involve the following steps:

  • function A:
    • push space for the return value
    • push parameters
    • push the return address
  • jump to the function B
  • function B:
    • push the address of the previous stack frame
    • push values of registers that this function uses (so they can be restored)
    • push space for local variables
    • do the necessary computation
    • restore the registers
    • restore the previous stack frame
    • store the function result
    • jump to the return address
  • function A:
    • pop the parameters
    • pop the return value

This is by no means the only way function calls can work (and I may have a step or two out of order), but it should give you an idea of how the stack is used to let the processor handle nested function calls.

Related Topic