Where are global (statically compiled) variables located?
Lets say I have the following program. Which part of memory is a
allocated in? Also is the behavior same for both c
and c++
?
// a is allocated in the ?
int a[3] = {1, 2, 3};
int main()
{
// x is allocated in the stack
int x[3] = {4, 5, 6}
// y is allocated in the heap
int* y = malloc(sizeof(int)*3);
}
In static storage, to use standard speak. It doesn't really say much of anything about how static storage should be implemented, other than that it should endure for the whole time of the program and that it should be implicitly zero initialized if no nonzero initializer is given.
Practically in ELF binaries, these variables are all concatenated into sections, which get, at load time, mapped onto segments, which are basically memory blocks with certain memory protection bits on or off. If the global variable is writable and initialized with a nonzero value, it'll go into an ELF section designated as .data
. zero
-initialized variables will go into .bss
(not part of the binary image so as to save space) and const
static variables will go into .rodata
, which will get mapped read-only, to facilitate write protection.
Your compiler's binutils (such as nm
or objdump
) can allow you to peek into the (implementation-dependent) details.
Where they are allocated is dependent on your machine architecture and your compiler and linker implementation (neither of which you have specified). the C++ Language Standard has nothing to say on the subject.
This is an implementation detail, the same is true for stack and heap. The language C doesn't have such concepts. If your implementation uses a heap, it probably also uses segments in a binary format provided by the OS. In that case, static variables are placed in a data
or bss
segment, so they are either part of the program itself (data) or allocated by the OS when loading the program (bss).
A somewhat common approach is to place default-initialized variables in bss
because this way, they don't increase the size of the executable file. For constant data, there's often a rodata
segment available, many C compilers put string literals there.
But bottom line is: you shouldn't care as C doesn't specify this and there are platforms that don't provide segments, or a heap, ...
链接地址: http://www.djcxy.com/p/82508.html上一篇: 常量变量存储在C中哪里?
下一篇: 全局(静态编译)变量位于何处?