1
int t[1000000];
int main(){}

This code (as a .cpp file) produces a small binary when compiled with g++. If I would later use the array t, it would have all it's elements set to 0.

int t[1000000]={1,2,3};
int main(){}

This one, even if compiled with optimization for size (-Os), produces a binary file that is nearly 4M big. The array t is the same as in the first example, except t[0], t[1] and t[2] are set to 1, 2 and 3 respectively. Why does storing those three numbers require so much extra file size?
tested on linux, gcc version 5.4.0

JJJ
  • 32,902
  • 20
  • 89
  • 102
Typical User
  • 153
  • 8
  • In the first example, `t` is likely stored in the `.bss` segment, whereas in the second example, `t` is likely stored in the `.data` segment. See [Data segment (Program memory)](https://en.wikipedia.org/wiki/Data_segment#Program_memory) and [Why is the .bss segment required?](https://stackoverflow.com/questions/9535250/why-is-the-bss-segment-required) – Cornstalks Oct 29 '17 at 18:41
  • `int t[1000000]={1,2,3};` is going to initialize values. You get 1, 2, 3, and then 999997 zeroes. This has to go somewhere, and it sounds like the whole durn thing, zeroes and all, are getting stored. – user4581301 Oct 29 '17 at 18:50

1 Answers1

3

Zero-initialised data with static storage duration is normally stored very efficiently in an executable file. It consumes almost no space on the disk. The executable contains a couple of words that say how many zero-initialised bytes it needs and at which address, and that's it.

Statically-initialised data, on the other hand, is stored as literal bytes that represent its value, and it doesn't matter if most of these bytes are zeroes. The executable format is defined such that it needs to physically store all of them. There's no provision to specify "1, 2, 3 and the rest are zeroes" in a space-efficient manner.

When the executable is loaded into RAM, the loader allocates the required amount of memory for zero-initialised data and fills it with zero-valued bytes, so there is no saving of RAM, only of disk space.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243