LESSON 06 / UNDEFINED BEHAVIOR

“It worked” is not a warranty.

It compiled. You shipped it. An inspiring chain of unsupported conclusions.

2 MIN READ + QUIZJump to reality check ↓

The mess

“It worked on my machine.” Lovely. So does a smoke alarm with the battery removed. Very quiet. Excellent reviews.

Undefined behavior means C++ imposes no requirements for that behavior. A crash isn't guaranteed. Neither is your preferred answer. Your successful demo isn't a contract.

int count = std::numeric_limits<int>::max();
int next = count + 1; // Signed overflow. Optimism is not a larger type.

With <limits> included, this compiles. The addition exceeds int's range: signed overflow is undefined behavior, not guaranteed wraparound. Unsigned arithmetic has different rules.

The fix

Check the boundary before adding. A wider type helps only if the allowed results fit it. Use unsigned wraparound only when that's actually the intended behavior.

Out-of-bounds access, expired objects, and data races are other traps. Compilers optimize assuming defined code follows the rules. They haven't agreed to preserve your accident.

Use warnings, tests, and appropriate sanitizers. A clean run checks exercised paths, not every possible execution. Your green checkmark isn't a priest.

Ask your AI

Find lifetime, bounds, overflow, and race risks. Name each violated rule, fix the cause, and propose boundary tests and sanitizer checks.

“It compiles” means it compiles. Stop adding imaginary warranties.

Receipts: Expression rules · Data races · UBSan.

THE REALITY CHECK

Did that actually stick?

Three questions. “The AI said so” is not an answer.

1 / 3Signed integer addition overflows. What is guaranteed?
2 / 3An invalid access worked ten times. What does that prove?
3 / 3A sanitizer found nothing. Is all undefined behavior ruled out?

Choose one answer for each question.

KEEP GOING. ALL LESSONS ARE OPEN.See your progress →