The example below shows code using uninitialized array elements:
#include <stdio.h>
int main(void)
{
char str[10]; /* elements not initialized */
int val; /* variable not initialized */
printf("%s\n", str); /* no warning */
printf("%d\n", val); /* warning */
return 0;
}
gcc generates a warning for val but not for str:
$ gcc -Wall -c uninitialized.c
uninitialized.c:9:20: warning: variable 'val' is uninitialized when used here [-Wuninitialized]
printf("%d\n", val); /* warning */
^~~
uninitialized.c:6:12: note: initialize the variable 'val' to silence this warning
int val; /* variable not initialized */
^
= 0
1 warning generated.
The compiler probably concludes that str actually is initialized because the pointer itself has a value. It is just that its elements are not initialized. So the compiler is right.
On the other hand, the compiler explicitly decides not to insert any initialization of the elements here, so it is aware of the uninitialized elements in the array. Then why does it not warn about that?
Are there any compiler settings or other tools that can help to detect this at compile time? I am interested in any C-compiler, not just gcc.