In its simplest form the program is
int main(){
int x;
scanf("%d",x);
}
When we give this program any numeric value as input it fails by producing a segfault signal which is what we should expect.
But if we instead give it any alphanumeric value it does not fail.
What is going on in the scanf
that produces this behavior?
This is the backtrace from gdb when running it with a numeric value:
(gdb) bt
#0 0x00000034e7456ed0 in _IO_vfscanf_internal () from /lib64/libc.so.6
#1 0x00000034e74646cd in __isoc99_scanf () from /lib64/libc.so.6
#2 0x0000000000400553 in main ()
So why is it not failing for any alphanumeric value like 'a' or 'dfgb'?
Section 7.21.6.2/10 of the standard say:
If the input item is not a matching sequence, the execution of the directive fails: this condition is a matching failure.
and 7.21.6.2/4:
The fscanf function executes each directive of the format in turn. When all directives have been executed, or if a directive fails (as detailed below), the function returns. Failures are described as input failures (due to the occurrence of an encoding error or the unavailability of input characters), or matching failures (due to inappropriate input).
As your input provides no good parsable integer, scanf
just returns 0 to signal that no conversion was made from input and do not try to dereference the argument you passed.
This answer was edited to cite the standard about that point, thank to @Zwol.