Introduction

What is undefined behavior (UB)? According to the ISO C++ Standard (§1.3.24, N4296), it is “behavior for which this International Standard imposes no requirements.”

This means that when a program encounters UB, it is allowed to do whatever it wants. This often means a crash, but it may simply do nothing, make demons fly out of your nose, or even appear to work properly!

Needless to say, you should avoid writing code that invokes UB.

Remarks

If a program contains undefined behavior, the C++ standard places no constraints on its behavior.

An implementation may document the result of an operation that produces undefined behavior according to the standard, but a program that depends on such documented behavior is not portable.

Why undefined behavior exists

Intuitively, undefined behavior is considered a bad thing as such errors can’t be handled graciously through, say, exception handlers.

But leaving some behavior undefined is actually an integral part of C++‘s promise “you don’t pay for what you don’t use”. Undefined behavior allows a compiler to assume the developer knows what he’s doing and not introduce code to check for the mistakes highlighted in the above examples.

Finding and avoiding undefined behavior

Some tools can be used to discover undefined behavior during development:

Undefined, unspecified and implementation-defined behavior