Undefined Behavior vs. Unspecified Behavior

Undefined Behavior vs. Unspecified Behavior

The terms “undefined behavior” and “unspecified behavior” are not interchangeable. Undefined behavior indicates that an implementation may behave unpredictably when a program reaches a certain state, which almost without exception is a result of a bug. Undefined behavior can be manifested as a run time crash, unstable and unreliable program state, or–in rare cases–it may even pass unnoticed. Examples of undefined behaviors include an attempt to write to a buffer past its boundary, accessing an out of range array subscript, de-referencing a dangling pointer or deleting a non-NULL pointer more than once.

Unspecified behavior, on the other hand, is a consistent and documented behavior that a certain implementation employs in cases that are left intentionally unspecified by the C++ Standard–usually, to allow efficient and simple compiler implementation on various platforms. Examples for unspecified behaviors include the size of an int, whether a char is unsigned or signed by default, the size of a pointer, or the underlying type representing a bool. It is guaranteed that the behavior of a certain implementation in such cases is consistent. For instance, all variables of type int are guaranteed to have the same size on the same machine. It is not guaranteed, however, that on another machine, int variables will occupy the same size.

To sum up, unspecified behavior is usually something you shouldn’t worry about, unless your software is required to be portable. Conversely, undefined behavior is always undesirable and should never occur.

See also  Why ChatGPT Is So Important Today

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist