Published 2026-11-28
Undefined behaviour (UB) means the C++ standard makes no promise about what happens. The program may crash, print garbage, or seem to work perfectly.
Classic causes: reading past the end of an array, using an uninitialised variable, signed integer overflow, and using freed memory.
Turn on compiler warnings, use .at() while learning, and initialise every variable. These habits remove most UB from student code.
int nums[3] = {1, 2, 3};
int x = nums[3]; // undefined behaviour: index 3 is out of bounds