Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are arrays initialised (to zero) in C by the compiler? [closed]

Disclaimer: I might have misunderstood how arrays are created, allocated and initialised. If so, please try to read between the lines.

If I create an array by doing

int array[15] = {0};

All elements of array the compiler will initialise the elements to 0. How is this done by the compiler? Does the compiler insert a loop that iterates the allocated memory and sets each element to zero? Does size impact performance? I.e. does it takes longer time to initialise an array of double size (30)? How much longer? Double? Logarithmic? Power of 2?

Only asking out of curiosity.

like image 514
T'n'E Avatar asked Dec 19 '22 01:12

T'n'E


1 Answers

I assume, you are talking about global variables/arrays.

Actually, it is not compiler task (if we are talking about modern OSes). Compiler just marks this object as zero-initialized.

Then, linker puts this object in section, that should be initialized with zeros. In ELF this section is named .bss. Usually, this section has no data (because there are only zeroes), but it has size.

And then, when loader loads your program into memory, it knows, that it should zero out memory that belongs to .bss section.

If we are talking about stack-based (local) variables, then compiler just calls memset()

like image 55
werewindle Avatar answered Mar 09 '23 00:03

werewindle