'Where are functions stored in memory?
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 1:[1]
The variable inside function are stored in stack.
And every linking and addressing part is done by linker.
In simple words linker decides what absolute address to give to what label or function and compiler decides how they will be arranged and will be able to address each other.
Compiling takes four steps:
Preprocessing [in which header file and microprocessor worked upon].
Compiling[In which they are converted into assembly code]
Assembly[In which codes are converted into machine level language but have relative addressing in respect to there starting]
Linking[When absolute address is given so when loaded they can address each other and files and linked in one]
#I think these last lines can help you
Functions and variable are labels and every label is translated into address. The code that runs on machine have address that represent these labels. And not only c but every compiled language goes through it. As on machine its machine code or just wiring.
Say if you not understood anything. Will be glad to help you
Solution 2:[2]
include <stdio.h>
void g()
{
int a=7;
}
int main()
{
//printf("%d\n",sizeof(g()));
//you cant use sizeof(g()) its a functiona and
//function not have anysize
printf("%p",&g);
//even you can't use here int a=7 that you declared in void g() as it is local to
//that function and this function cant access any function local variable
//but what it returns
return 0;
}
If you want to see addressing than see this:
0000000000001135 <g>:
1135: 55 push %rbp
1136: 48 89 e5 mov %rsp,%rbp
1139: c7 45 fc 07 00 00 00 movl $0x7,-0x4(%rbp)
1140: 90 nop
1141: 5d pop %rbp
1142: c3 retq
0000000000001143 <main>:
1143: 55 push %rbp
1144: 48 89 e5 mov %rsp,%rbp
1147: 48 8d 35 e7 ff ff ff lea -0x19(%rip),%rsi # 1135 <g>
114e: 48 8d 3d af 0e 00 00 lea 0xeaf(%rip),%rdi # 2004
<_IO_stdin_used+0x4>
1155: b8 00 00 00 00 mov $0x0,%eax
115a: e8 d1 fe ff ff callq 1030 <printf@plt>
115f: b8 00 00 00 00 mov $0x0,%eax
1164: 5d pop %rbp
1165: c3 retq
1166: 66 2e 0f 1f 84 00 00 nopw %cs:0x0(%rax,%rax,1)
116d: 00 00 00
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Caleb |
| Solution 2 | OSdev |
