In the C language, variables are initialized differently depending on the storage class:
Example of differences:
void example() { int a; // automatic, uninitialized static int b; // initialized to 0 printf("a=%d, b=%d\n", a, b); } int c; // global, initialized to 0
Errors arise from incorrect assumptions about initialization. For safety, always explicitly initialize your variables.
Is an automatic local variable initialized to 0 if it is declared at the function level outside of a block?
Answer:
No! Even if the variable is declared at the beginning of the function, if it is not explicitly initialized, it contains garbage:
void f() { int x; printf("%d\n", x); // UB: x is uninitialized }
Story
In banking software, a missed initialization of a counter inside a function led to it sometimes being a huge negative number — the result: erroneous bonuses were credited to the client, the bug was discovered only with real data.
Story
An image multimedia handler initially assumed that static arrays were always filled with zeros. After switching to another compiler (with a non-standard environment), a segmentation fault was discovered — part of the memory had not been physically allocated to the process.
Story
In a cryptographic library, the developer did not initialize the temporary password buffer, believing that the buffer from the global section was filled with zeros, but there was a case with memory where old sensitive data remained. This led to a leak of passwords during a dump.