My understanding is that static memory such as the stack, virtual tables, static variables, ect are all allocated at "compile time" as opposed to dynamic memory which is allocated at runtime. But I'm confused as to what this means. As I understand it the compiler/linker interprets the written code, translates it into machine language, and then assembles it into an executable. Is the implication that the stack and all static memory are part of the executable file itself?
-
1Well, for one, the stack isn't really static memory. It's often implemented as a region of memory that's allocated to the program at *load* time. Other stuff (like global static variables) *may* be coded into the executable file by the linker, but that's not a requirement. – Adrian Mole Aug 22 '21 at 23:21
1 Answers
My understanding is that static memory such as the stack ... are all allocated at "compile time"
Sort of. It is determined at compile time how the memory will be allocated when a block is entered. But the allocation doesn't happen until runtime.
Is the implication that the stack and all static memory are part of the executable file itself?
Depends on what you mean by that. The executable file does indeed contain information about memory that will be allocated. For example, if the compiler knows that it needs to allocate 64 bytes on the stack, then there would be an instruction that adjusts the frame pointer by 64 bytes (or something along those lines).
None of this is specified by the language itself, so everything is up to the language implementation to decide and varies between different language implementations. My explanation is simplified and describes a hypothetical language implementation and might not be accurate to whatever language implementation you use.

- 232,697
- 12
- 197
- 326
-
Ok so it's not so much that the memory is allocated at compile time but that the compiled program knows exactly how much memory it will need for its static data at execution? – NickyBugs Aug 22 '21 at 23:55
-
@NickyBugs Indeed. Why would a program consume any memory before the it is executed? – eerorika Aug 22 '21 at 23:59
-
Yeah that's what was confusing me about the phrasing "allocated at compile time" which every source I was consulting used. – NickyBugs Aug 23 '21 at 00:27