Denis Steinman
Denis Steinman

Reputation: 7799

Where does compiler store constant arrays?

Maybe it's a stupid question. But I want understand it and cannot find an answer. When I write smth like below:

int test[1000000] = {0};

Will this array include in compiled program code? Or only instruction to hold available memory for this array?

I want understand whether C++ includes all array's values in binary code in this case or allocates memory at runtime?

Upvotes: 3

Views: 230

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

The answer to this question is strongly dependent on the data format in use.

For example, when you write this

int test[1000000] = {1, 2, 3};

and use a compiler that produces an ELF executable, the compiler emits the data for 1, 2, 3, but sets the size of the section to sizeof(test). When ELF executable is loaded into memory, the loader stores 1, 2, 3 in the first four ints, and zeros out the remaining section to the end. See this Q&A for more details on ELF's handling of trailing zeros in a data section.

Other executable formats have similar capabilities: essentially, instead of storing zeros in the text section, they store instructions for the loader to set some static memory aside, and clear it out before executing the program.

Note: The answer assumes that test is allocated in the global scope.

Upvotes: 5

Related Questions