简体   繁体   中英

How to make g++ refuse any code that exhibits undefined behaviour?

I would like to add a CXXFLAG to my build systems that force the entire code-base to be well-defined. So every piece of code that exhibits undefined behaviour in a static fashion, should be refused by the compiler.

For instance reinterpret_cast<A*>(someIntPtr)->aMember is without any runtime context undefined (a), while int i = bar(); i /= i; int i = bar(); i /= i; could result in undefined behaviour (b) depending on the runtime evaluation of bar() (which could return zero).
I only expect the (a) cases to be caught, not necessarily the (b) cases.

I'm not sure that your goal is computationally feasible.

However, you'll get moderately close with -Wall -Wextra -Werror ; look at the other warning options to see what else you want to enable.

Impossible. There are many, many instances of UB which are not detectable. That's arguably the reason why they are UB, exactly because it is impossible to catch these problems at compile time.

Some examples:

  • int n = 0; std::cin >> n; ++n; Signed overflow is UB. (Example of value -dependent UB.)

  • double d = std::sin(some_user_value); int n = d; UB if d cannot be represented as an int . (Ditto.)

  • compile multiple translation units with differing class definitions visible to each. (Example of UB due to limitations of the compilation model.)

  • any race condition is by definition UB. (Example memory-model related UB.)

  • misuse of variadic functions. (Example of UB due to the type system.)

You can use static code analysis tools similar to the classic lint . You may already have cppcheck .

You can't, and you shouldn't rely on the compiler to point out UB for you.

You best bet is to use -Werror to cause all warnings to become errors, and then enable a great deal of warnings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM