Use of an uninitialized variable
suggest changeint a;
printf("%d", a);
a has automatic storage duration and is never initialized. Its value is indeterminate. Using that value is undefined behavior when the object could have been declared register (its address is never taken). It is also undefined behavior if the value is a trap representation.
Objects with static or thread storage duration, including file-scope objects without the static keyword, are initialized to zero unless the declaration provides another initializer. See Storage duration and linkage. The following is defined:
static int b;
printf("%d", b);
A very common mistake is to not initialize the variables that serve as counters to 0. You add values to them, but since the initial value is garbage, you will invoke Undefined Behavior, such as in the question Compilation on terminal gives off pointer warning and strange symbols.
Example:
#include <stdio.h>
int main(void) {
int i, counter;
for(i = 0; i < 10; ++i)
counter += i;
printf("%d\n", counter);
return 0;
}
C02QT2UBFVH6-lm:~ gsamaras$ gcc main.c -Wall -o main
main.c:6:9: warning: variable 'counter' is uninitialized when used here [-Wuninitialized]
counter += i;
^~~~~~~
main.c:4:19: note: initialize the variable 'counter' to silence this warning
int i, counter;
^
= 0
1 warning generated.
C02QT2UBFVH6-lm:~ gsamaras$ ./main
32812
The above rules are applicable for pointers as well. For example, the following results in undefined behavior
int main(void)
{
int *p;
p++; // Trying to increment an uninitialized pointer.
}
p++ already has undefined behavior. It uses the indeterminate value of p. A later dereference is not required for the program to be undefined, and the increment is not required to trap.