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 identify the earliest point in a program that undefined behavior could cause problems.
Here is an example to illustrate my question.
void causeUndefinedBehavior()
{
//any code that causes undefined behavior
//every time it is run
char* a = nullptr;
*a;
}
int main()
{
//code before call
//...
causeUndefinedBehavior();
//code after call
//...
}
From my understanding, the possible times undefined behavior could be evoked (not necessarily manifested) are:
- When
causeUndefinedBehavior()is compiled. - When
main()is compiled. - At the time the program is run.
- At the time
causeUndefinedBehavior()is executed.
Or is the point where undefined behavior is evoked completely different for every case and every implementation?
In addition, if I commented out the line where causeUndefinedBehavior() is called, would that eliminate the UB, or would it still be in the program since code containing UB was compiled?
As your code somewhat demonstrates, undefined behavior is almost always a condition of runtime state at the time the behavior is attempted. A slight modification of your code can make this painfully obvious:
You could execute this a thousand times or more and never trip the UB execute-condition. that doesn’t change the fact the function itself is clearly UB, but detecting it at compile time in context of the invoker is not trivial.