How to spot undefined behavior

后端 未结 10 514
梦毁少年i
梦毁少年i 2021-01-11 11:45

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

10条回答
  •  迷失自我
    2021-01-11 12:04

    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.

提交回复
热议问题