I\'m aware that undefined behavior can potentially cause anything, which makes any program containing UB potentially meaningless. I was wondering if there is any way to iden
I think it depends on the type of undefined behavior. Things that would affect something like structure offsets could cause undefined behavior, which would show up any time code that touches that structure is executed.
In general, however, most undefined behavior happens at run time, meaning only if that code is executed will the undefined behavior occur.
For example, an attempt to modify a string literal has undefined behavior:
char* str = "StackOverflow";
memcpy(str+5, "Exchange", 8); // undefined behavior
This "undefined behavior" will not take place until the memcpy
executes. It will still compile into perfectly sane code.
Another example is omitting the return from a function with a non-void return type:
int foo() {
// no return statement -> undefined behavior.
}
Here, it is at the point at which foo
returns that the undefined behavior occurs. (In this case, on x86, whatever happened to be in the eax
register is the resultant return value of the function.)
Many of these scenarios can be identified by enabling the a higher level of compiler error reporting (eg. -Wall on GCC.)