Is there any way to know if you program has undefined behavior in C++ (or even C), short of memorizing the entire spec?
The reason I ask is that I\'ve noticed a lot
It's not possible to detect undefined behavior in all cases. For example, consider x = x++ + 1;
. If you're familiar with the language, you know it's UB. Now, *p = (*p)++ + 1;
is obviously also UB, but what about *q = (*p)++ + 1;
? That's UB if q == p
, but other than that it's defined (if awkward-looking). In a given program, it might well be possible to prove that p
and q
will never be equal when reaching that line, but that can't be done in general.
To help spot UB, use all of the tools you've got. Good compilers will warn for at least the more obvious cases, although you may have to use some compiler options for best coverage. If you have further static analysis tools, use them.
Code reviews are also very good for spotting such problems. Use them, if you've got more than one developer available.