How to force g ++ to abandon code showing undefined behavior?

I would like to add CXXFLAG to my build systems, which strongly define the entire CXXFLAG . Therefore, each piece of code that demonstrates undefined behavior in a static way must be rejected by the compiler.

For example, reinterpret_cast<A*>(someIntPtr)->aMember does not have any runtime context undefined (a), but int i = bar(); i /= i; int i = bar(); i /= i; can lead to undefined (b) behavior depending on the runtime estimate of bar() (which can return zero).
I expect that (a) the cases will be caught, and not necessarily (b).

+4
source share
4 answers

I'm not sure your goal is computationally feasible.

However, you will be moderately close with -Wall -Wextra -Werror ; see other alert options to see what else you want to enable.

+7
source

impossible. There are many examples of UB that are not detectable. This is perhaps the reason why they are UB, precisely because it is impossible to catch these problems at compile time.

Some examples:

  • int n = 0; std::cin >> n; ++n; Raised Overflow - UB. (An example of a value-dependent UB.)

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

  • compile multiple translation units with different class definitions visible to each. (UB example due to compilation model limitations.)

  • any race condition as defined by UB. (An UB example associated with a memory model.)

  • misuse of variational functions. (UB example due to type system.)

+6
source

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

+1
source

You cannot, and you should not rely on the compiler to tell you UB.

It is best to use -Werror to trigger all warnings, and then turn on a large number of warnings.

+1
source

Source: https://habr.com/ru/post/1387132/


All Articles