Reputation: 732
In the following code segment:
int func()
{
int a=7;
return a;
}
Is the code segment where the value 7 is stored in the executable? Or is it in data segment or in the code segment? Will the answer depends on the Operating system or the compiler?
Upvotes: 1
Views: 367
Reputation: 1
Since a
is implicitly auto
(i.e. is not extern
or static
) it is stored in the call stack frame.
In fact, the compiler may optimize that: probably, in your case, when optimizing, it will stay in a register (or be constant propagated and constant folded): no need to allocate a call stack slot for your a
This is of course compiler, target platform, and operating system dependent. For the GCC compiler, understand the Gimple internal representation (thru -fdump-tree-all
, or using the MELT probe) and look at the generated assembler code (use -fverbose-asm -S -O
)
See also this answer which gives a lot of references.
GCC 4.8 on Linux/x86-64 compiles (with gcc -S -fverbose-asm -O
) your function into:
.globl func
.type func, @function
func:
.LFB0:
.cfi_startproc
movl $7, %eax #,
ret
.cfi_endproc
.LFE0:
.size func, .-func
So you see that in your particular case no additional space is used for 7
, it is directly stored in%eax
which is the register (defined in the ABI conventions) to hold its returned result.
The value 7
is stored in the machine code, inside the movl
machine instruction. When func
is executed, that 7 is loaded into register %eax
containing the returned result of func
.
Upvotes: 2
Reputation: 2327
Depending on the example code, variable "a" goes in call stack, place to store local variables along with function call information like program counter, return addr etc
Upvotes: 0
Reputation: 21460
Each executable format has some sections. One of them is text
, contains the assembly - binary code. One of them is heap
where malloc
-ed data is found and on is stack
where local variables are stored. There are several others but it doesn't matter now. The above three are common everywhere.
Now, local data like your a
resides on the stack. In the executable file, the value is stored in the text
section.
I've added a main
to your code (returning 0), compiled with -g
then did objdump -CDgS a.out
and searched for 0x424242
(I've replaced your 7
with a value with lesser chance of randomly occurring in code).
00000000004004ec <func>:
int func()
{
4004ec: 55 push %rbp
4004ed: 48 89 e5 mov %rsp,%rbp
int a=0x42424242;
4004f0: c7 45 fc 42 42 42 42 movl $0x42424242,-0x4(%rbp)
return a;
4004f7: 8b 45 fc mov -0x4(%rbp),%eax
}
4004fa: 5d pop %rbp
4004fb: c3 retq
As you see, c7 45 fc 42 42 42 42
means that the value is stored in the generated file. Indeed, this is the case when looking at the binary via xxd
:
$ xxd a.out | grep 4242
00004f0: c745 fc42 4242 428b 45fc 5dc3 5548 89e5 .E.BBBB.E.].UH..
You can recognize the above assembly line in the xxd
snippet.
Upvotes: 3