Stack for Function Calls

Learn the internals of the function call mechanism.

Problem statement

Our goal is to explore stack usage for making function calls.

In the following example, main calls doubleNum. We want to figure out the internals of how the compiler performs the function call.

Press + to interact
#include <stdio.h>
int doubleNum(int x)
{
int y = x * 2;
return y;
}
int main()
{
int x = 5;
int result = doubleNum(x);
printf("result = %d\n", result);
return 0;
}

More precisely, what does the compiler have to do to make the call for doubleNum? We’ll figure out the requirements and then find possible solutions.

Calling the function

Well, the first thing to tackle is how the code jumps from executing func2 to func1 after the call. We need a way to tell the CPU that it should pause executing one function and start another.

We know by now that the code is loaded in memory when a program starts running. The operating system knows that programs start from the main function. After some preparations, the control jumps to main (the CPU executes the code from main).

How does the CPU know what code to execute?

The CPU has a register called eip or instruction pointer register. Recall that registers are tiny blocks of memory very close to the CPU.

The eip register holds the memory address of the instruction currently executed. Therefore, to start the execution of main, we need to put its address inside eip.

The high-level view is that the CPU holds the address of the instruction to execute in a memory location.

It may ...