parts/6.56.UndefinedBehaviour-EWF.md

6.56 Undefined Behaviour [EWF]

6.56.1 Applicability to language

The vulnerability as described in ISO/IEC 24772-1 clause 6.56 applies to C++. In ISO/IEC 14882:2023, the terms “undefined behaviour” and “ill-formed, no diagnostic required” expose situations to be avoided.

For the special case of constant expressions, compilers are required to detect and reject undefined behaviour during the evaluation of constant expressions in the core language. It is unspecified whether or not undefined behaviour in the standard library is detected during constant expression evaluation.

C++ compilers and static analysis tools can often detect code that can lead to undefined behaviour and provide diagnostic messages to that effect. Use of multiple compiler tool chains during development increases the likelyhood that such behaviours will be detected. Similarly, runtime tools such as address sanitizers and thread sanitizers can be used during development to detect and report concrete instances of undefined behaviour. In addition, recent C++ language revisions have provided safer alternatives some standard library calls that can lead to undefined behaviours. For example,the calls std::stoi or std::from_chars provide equivalent functionality to std::atoi but without the the risk of undefined behaviour.

Code with UB often appears to work correctly but masks situations that can result in serious consequences, for example:

Undefined behaviour often manifests in code distant from where the UB occured, resulting in extremely hard to find bug. Therfore, retrospective detection of undefined behaviour is exceedingly difficult and resource intensive. Many undefined behaviour situations can be avoided through the use of explicit tests or assertions for undefined behaviour situations, such as null-pointer tests before assessing via a pointer, array-bounds checks before access to array members, and floating-integeral conversions that cannot be represented in the target type. Modern compilers can eliminate such tests when they know that the check will succeed.

6.56.2 Avoidance mechanisms for language users

To avoid the vulnerability or mitigate its ill effects, C++ software developers can: