C Program memory map [closed]
- stati开发者_StackOverflow社区c int i=0; where will be the variable i allocated? Is it in BSS or initialized data segment?
- where will be variables of storage class 'extern' and 'register' are stored?
I possible please provide code Snippet to crosscheck the above
It's impossible to say for sure without knowing the specific implementation you're dealing with. In some cases, static int i=0;
will be stored in an initialized data segment because you've supplied an initializer. In other cases, the BSS will be zero-initialized anyway, so the linker will put it there anyway. If you specified a different value (e.g., static int i=12345;
) then you'd have a much better assurance of its being placed in an initialized data segment.
extern
doesn't really determine where the linker will place the variable. It's pretty much as above: if the linker knows (or arranges) that BSS is zero-initialized, then something that's extern with no specified initializer may be in BSS. If BSS isn't zero-initialized, it'll normally have to be in an initialized data segment instead.
register
is basically equivalent to auto
-- they're both allocated at run time, typically either in a register or on the stack.
As far as verifying it, that gets to be even more dependent on the individual implementation. You'd typically find out by looking at something like a linker map file; if you want to figure it out on your own, it'll very likely involve looking at either the symbol format being used, or else spelunking the internals of the executable format for your system.
As was said before, it depends.
In my case (gcc & Linux), I decided to go and look:
int main ( int argc, char **argv )
{
static int initialized_static_var = 0;
static int uninit_static_var;
register int reg_var;
extern int extern_var;
return 0;
}
And then objdump -x on the executable file (edited for brevity):
0804a018 l O .bss 00000004 uninit_static_var.1704
0804a01c l O .bss 00000004 initialized_static_var.1703
Neither the register variable nor the unused extern show up in the symbol table, which makes sense if you think about it.
Read this: Where are static variables stored (in C/C++)?
then make your own snippets.
精彩评论