Undefined behavior in C ++
The situation when C ++ code is syntactically valid, but its behavior is not defined in the Standard, is often called simply undefined behavior in Russian-language literature. In the Standard itself, for such situations there are as many as 3 terms: undefined behavior , unspecified behavior and implementation-defined behavior . In this short note we will understand how they differ.
This term is used to describe situations where C ++ code is fully valid, but its behavior depends on the implementation (for example, the compiler or runtime), and this behavior is documented . For example, the size in bytes of a pointer or int type depends on the particular implementation or compiler settings, but this is described in the documentation, and you can rely on this documentation.
The term means that the behavior of valid C ++ code is not defined by the Standard and depends on the implementation, moreover, it is not documented (at least officially). Example: the procedure for calculating the values of function arguments is determined by the compiler, but nowhere is there a description of how. The standard tells us: these are behavioral features that are not fixed anywhere, therefore, you can not rely on them. Therefore, the behavior of your code should not depend on these features.
This is the most dangerous variant of uncertainty. In the Standard, it is used to describe behavior that can lead to completely unpredictable consequences. The most striking examples are accessing the boundaries of an array or dereferencing a pointer to a freed object. The worst part is that the program doesn’t have to end immediately or even produce any error, however, its behavior can no longer be relied on.
In conclusion, I remind you once again that all the above terms refer to syntactically valid code that will be successfully compiled (however, compilers often give warnings for the most obvious cases of undefined behavior ). Code that is invalid from the point of view of the Standard is called an ill-formed program .