What is it?
Undefined behavior.(Check ref-1, ref-2)
Why is it so?
From standard 7.21.6.1
The fprintf
function writes output to the stream pointed to by stream
,
under control of the string pointed to by format
that specifies how
subsequent arguments are converted for output.If there are
insufficient arguments for the format, the behavior is undefined
How to avoid?
Also when compiled with
gcc -Wall -Wextra -Werror progname.c
gives the error (due to -Werror
)
error: format ‘%d’ expects a matching ‘int’ argument [-Werror=format=]
printf("%d");
^
This was clear enough to tell you what is going wrong. But you didn't check.
then what is that the fetched value? is that just garbage value?
it is most likely that the printf
when sees the %d
specifier tries to read one int
variable's value from memory. But alas that memory don't contain anything meaningful to you. (Even accessing that memory might not be permitted.) And yes it's just some value - garbage value. Don't even think that everytime you will get some garbage value - don't rely on it or anything similar. It's undefined behavior. Next time it may crash your program or simply print my contact number.1,2
1. This last part of the answer explains the possible reason for that garbage print.
2. print my contact number
- is simply pointing out that it is just a garbage value which you shouldn't care about. Moreover it's undefined behavior - seeing even a garbage value is not something that is guaranteed to happen every single time.