I am correcting static analysis (MISRA-C-2012) violations, one rule of which (rule 9.3) states that variables shall be initialized before use.
For instance:
void bar_read(int * array)
{
printf("array[1]: %u\n",array[1]);
}
void bar_write(int * array)
{
array[1]=1;
}
int main(void)
{
#define FOO_SIZE 12
#ifdef MISRA_VIOLATION_DISABLED
int foo[FOO_SIZE] = {0}; //ok
#else
int foo[FOO_SIZE]; //violation
#endif
bar_read(foo);
bar_write(foo);
bar_read(foo);
return 0;
}
Some collegues of mine declared that they were removing variables initialization (for big arrays) foo[FOO_SIZE] = {0}; because it was reducing performances, which puzzled me.
In my understanding, zero-initialized variables are put in the bss section at compile time and there is no runtime performance impact.
Could I be wrong? Might it depends on the compiler? Is there any optimisation that makes it true?
An array defined with int foo[FOO_SIZE] (no static or extern) inside a function has automatic storage duration, meaning it is “created” (memory is reserved for it) each time execution reaches the block it is in and is “destroyed” (memory is released) when execution of that block ends. Because functions can be called recursively, memory for automatic objects cannot feasibly be reserved in the .bss section. The stack is generally used for them.
Further, even if they were in the .bss section, their lifetimes in the C model still begin and end each time the block they are in begins and ends. So, if they are initialized, they have to be initialized each time a new lifetime begins. Storing them in the .bss section would not save anything in this regard.
Further, if the .bss section is zero-initialized, that is not free. Whenever the operating system provides memory to back a zero-initialized section, it must clear that memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With