This is how functions work internally…

Shashwat Gupta
3 min readJul 25, 2022

--

Hey folks, it’s mesmerizing how functions work internally, what happens in memory, how the calling mechanism works, and much more….

So, before knowing what happens, we should know about :

a. Program Stack: A stack is a special area in memory that is used to store data temporarily. For functions, it holds all the function calls with the bottom element as the main function because it’s the first function in a program that is executed and goes to the bottom of the stack.

It works on LIFO (first-in-last-out) principle i.e. what goes in first comes out last.

b. Stack Frame: It is a buffer memory that is an element of the program stack and it has the data of the called function i.e. Return Address, Input Parameter, Local Variables, Register Savings.

c. Stack Pointer: It is the pointer that points to the stack frame in the program stack i.e. the most recent function called.

These three elements can be visualized as :

Visualization

Now, let’s get to the interesting part :

  1. Whenever a function is called, a new stack frame of the function is created with all the function data in it.
  2. The stack frame is pushed into the program stack.
  3. The stack pointer that always points to the top of the stack points to the stack frame pushed recently.
  4. When the function whose stack frame is at the top finishes execution, its stack frame is popped (deleted) of the stack i.e. the functions data is deleted.
  5. Now the control passes back to the function caller from where it was called or it can be said that the control goes to the stack frame which is now at the top after the frame that was above it got popped off.

The above process can be explained via the pseudo-code :

pseudocode
The working

As we know, main_function is always executed first in a program and according to the pseudocode above, (see in fig. a) it called func1() and as it was called, its stack frame was generated with all its data, and was pushed (inserted) in the program stack with the stack pointer pointing to it as it is the frame pushed recently. When func1() started executing, (see in fig. b) it called func2(), and similarly, its stack frame also got pushed into the stack and the pointer points to it. When func2() finishes its execution, its stack frame consisting of all its data got popped (deleted) off the stack (see in fig. c) and the stack pointer started pointing to func1() which is the function that called func2() and also it’s stack frame is at the top. And when each function’s execution will get over, their frames will be popped and the stack will be emptied.

Hope you understood….

Thanks for reading❤️

--

--

Shashwat Gupta

Tech Nerd | Music | Building Connections | Technical Blogging