Let's take a simple example:
char c;
scanf("%d", &c);
scanf
with a %d
format requires an argument of type int*
. It will try to read a value from stdin
and, if successful will store an int
value in the object to which the argument point.
So if c
were of type int
, this would be fine.
The standard says that if the type of the argument is incorrect for the format string, the behavior is undefined. That's all it says about it. That means that it might behave exactly the way you want it to (which is in a sense the worst possible outcome, because it means you have a bug that's difficult to diagnose, and might show up at the worst possible moment). Or it could cause your program to crash, or allow it to proceed with invalid data.
So what's actually likely to happen?
scanf
, if it successfully reads an int
value, will try to store that value in an int
object located where c
is. If char
is 1 byte (which it is by definition) and int
is 4 bytes (which is very common), then it will store 4 bytes of data to a 1-byte location. The remaining 3 bytes can clobber whatever is in the memory adjacent to c
.
If those 3 bytes aren't allocated to anything, there might not be a visible symptom. If some other declared object is stored there, you could clobber that object. If some implementation-specific data is stored there (say, your function's return address), Bad Things Could Happen.
"Undefined behavior" means that your code is breaking the rules -- but it doesn't mean that the implementation has to do anything about it. The burden is on you, the programmer, to avoid breaking those rules, with or without the compiler's help.
Many compilers will, if invoked with the right options, warn you about this particular issue. Do not ignore those warnings.
You can say a lot about what's likely to happen in the presence of undefined behavior if you know something about the particular implementation you're using. And sometimes that can be useful. More often, though, especially if you're writing new code, your time is better spent fixing your code rather than figuring out all the myriad ways it can go wrong.