Hi!
I was coding the Dynamic Segment Tree in C++ by storing all the data of a node in a struct. While coding, I found that the following small piece of code generated a very large binary file on compilation (32 MB). Even, the compilation time was longer than usual.
However, while doing a slight change in the above code, the size of the binary file reduced to 20 KB (that's around 1600 times smaller).
I use the following command to compile: g++ -o out file.cpp
, and the size of the out
file (Binary File) is mentioned above.
If I initialize those variables using a constructor or even if I add a default constructor (which does nothing), then the size of the Binary File reduces to 20 KB.
The size of all the binary files mentioned is based on my machine. It may vary on other machines.
But why should someone worry about this?
Well, one should worry because the Online Judges have a size limit for the binary file generated. I just submitted the same code on a random problem on codeforces and got COMPILATION_ERROR
. Submission: 86340669
Checker comment:
Can't compile file: Compiled file is too large [34411089 bytes], but maximal allowed size is 33554432 bytes [CompileRequest {id='program.cpp', description='', file='program.cpp', resources='', type='cpp.g++17'}]
The Binary File may even become as large as 1 GB
If I change N to 2e6, add four variables in the struct, initializing all of them to 1, and then compile the file — the binary file can become as large as 1 GB (it will definitely take a long time to compile, may freeze your machine too).
How to initialize variables then?
In my opinion, the best way would be to initialize all the variables using a default constructor, rather than initializing their values in the declaration itself. It will work either way, but using a default constructor is the most appropriate way of initializing variables in a struct, and it is safe too.
About why this happens, a probable guess is, it depends on the way how compiler allocates memory. If 'all' the variables are initialized simultaneously in a struct, then the compiler allocates memory differently, as compared to when 'some' of the variables are initialized.
I'm not sure, but this is just a guess.
So, anyone who can explain why this happens, in a better way?
- Adding 5 variables, but leaving one of them uninitialized — 20 KB.
- Initializing all the variables to 0 — 20 KB.
- Using a default constructor to initialize values — 20 KB.
- Using a default constructor that does nothing — 20 KB.
- Initializing all the variables, such that at least one of them has a non-zero value — 32 MB.
- And why is the size of the file TOO LARGE (1600 times larger?)