[SOLVED] Where are functions stored in memory?

Issue

Where are functions stored in memory in c?
Can anyone explain it in simply language?

#include stdio.h>

void g()
{
    int a=7;
}

int main()
{
    printf("%d\n",sizeof(g()));
    printf("%p",&g);

    return 0;
}

The output of the following program is

1
00007ff6ee001581

and where the variable inside the function is stored and linked with function address

Solution

The output of the following program is

The second line of output is a pointer to the code for the function g. It’s the address of that function, and it’s the literal the answer to your question about where the function is stored.

and where the variable inside the function is stored and linked with function address

The variable a is a local variable, so it only exists while the function is executing. Usually the compiler will create space for local variables on the stack — that’s one of the main reasons for having a stack. Once the function returns, its local variables are popped off the stack and they cease to exist. In other words, a isn’t connected to the location of g at all.

Local variables are typically referenced via some offset from the stack pointer. When you call a function, a stack frame is created on the stack. The stack frame basically consists of storage for all the function’s local variables, and also the address of the previous stack pointer and the return address. The function’s code then starts executing, and since the compiler knows the relative address of each variable (i.e. where it is in the stack frame), it can easily calculate the absolute address. Most processors have instructions that make relative addressing easy for exactly this reason. When the function exits, the stack pointer is set back to the previous stack frame and the processor jumps to the return address. But this is just one possible implementation; on modern processors that have lots of registers, local variables may not even be stored on the stack — they may just end up in registers.

Answered By – Caleb

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.