This isn’t a good mental model. The compiler isn’t limited to just affecting the code
after the undefined behavior. It is allowed to assume undefined behavior never happens
for the entire program.
For example, this code with an improper guard:
if (!p) puts("error");
printf("%d", *p);
Since the program dereferences p in line 2, and dereferencing null is UB, the compiler is allowed to assume p is never null, so it’s allowed to delete line 1, even though it would have executed before the point where UB would happen.
Even worse, the compiler isn't just allowed to not do things you told it to do, it's also allowed to do anything too.
For example, this code with an improper guard:
Since the program dereferences p in line 2, and dereferencing null is UB, the compiler is allowed to assume p is never null, so it’s allowed to delete line 1, even though it would have executed before the point where UB would happen.Even worse, the compiler isn't just allowed to not do things you told it to do, it's also allowed to do anything too.