I’m in confusion. Does the allocation of automatic, static and global variables take place at compile time or run time?
The thing I know is that at compile time, the source code is translated to machine language.
When the compiler finds a statement like int a;, it writes the instruction. Do any extra things happen, like memory allocation, at compile time?
What happens when the .exe file will be executed?
Whether computer (OS) or compiler will allocate sufficient memory of holding an integer at runtime or compile time.
Also it is said that the address of a global variable is a compile-time constant. What does it mean?
Please help to solve each question, especially the last one.
Static global variables are allocated memory resources either at compile-time or run-time. This depends on whether the static variables are zero-initialized, or if they have initial constant values. For instance, code like
won’t take up any room in the executable … in other words the compiler/linker will not allocate memory in the executable for that array since it doesn’t contain anything. It will leave a stub though that indicates when the executable is launched, memory must be allocated for the array. Once you launch the executable, the OS sees the stub left by the linker, and allocates and zero-initializes the memory for the array (as well as other memory for the heap, etc.). On the other-hand,
will take up space in the executable since it is initialized with constant values at compile-time. Thus the compiler will emit code in the
datasection of the assembly file it generates that allocates storage for the array. The linker will then properly layout the data-section and code sections of all the assembly files that are being linked into the final executable. When the OS loads the executable into memory, the memory for the array is already part of the executable’s memory “foot-print”.Automatic variables, since they are allocated on the stack during the execution of code, are allocated at run-time.
That’s a bit misleading … in C you can’t know the exact memory-address of any global variables until the linker has created the executable, and the OS has loaded the executable into memory. The only way this could be done would be if you hand-assembled a file and created a flat-binary that was specifically loaded into a given address by the operating system, but modern operating systems don’t let you do that. Instead, the addresses of global variables are given place-holders by the linker so that they can be substituted with the correct values when the OS loads the executable at run-time. So while the memory address is “constant” in the sense that it won’t change over time while the program is running, its actual value is not assigned at compile-time.