Search code examples
compile-timestatic-memory-allocation

Memory allocation to static variables (Compile time memory allocation)


Memory allocation to static variables is done at compile time.

  1. If I compile my application number of times, will memory be allocated every time?
  2. If yes, then by the time, it may consume complete memory of my computer. Practically, it never happens, How?
  3. Also, when we run the executable of the same application on some other computer, It runs successfully. How it finds the static variables in other computer's memory, if it was compiled on other computer.
  4. Also, If I start many instances of the same application, will copy of static variables be created for all the instances or single static variable be shared among all instances? I think, copy will be created. But here I have doubt that memory was allocated at compile time and one instance of the application can use that memory, so how other instances will allocate memory to that static variables.

    Overall, I have doubt over What does "memory allocation at compile time" actually mean?


Solution

  • You've misunderstood the statement 'memory allocation at compile time'. What is meant by that is that the compiler writes data to the binary that it produces that indicates that the memory should be set aside when the program is loaded by the operating system.

    In particular, the field is usually stored in a section in the output file that is called the BSS. The compiler puts the static variable declaration in the BSS, the OS's program loader reads out the BSS section when loading the program, and sets aside enough memory in the freshly created process to store the BSS.

    Every time the program is launched, that is every time a new process is created, new memory is set aside for that process. This includes the memory needed for the BSS aka static variables.