⚙️ C++ Advanced

What is undefined behavior in C++ and how do you avoid it?

Why Interviewers Ask This

Advanced questions like this reveal whether a candidate has internalized C++ deeply enough to make architectural decisions. Strong answers demonstrate both breadth and depth of experience.

Answer

Undefined behavior (UB) occurs when a C++ program violates the language rules — the standard makes no guarantee about what happens. The compiler assumes UB never occurs and may optimize around it, producing surprising results: crashes, wrong output, security vulnerabilities, or seemingly correct behavior that breaks on a different compiler/optimization level. Common sources of UB: (1) Out-of-bounds access: int arr[5]; arr[5] = 10; // UB -- buffer overflow; (2) Null/dangling pointer dereference: int* p = nullptr; *p = 5; // UB delete p; *p = 5; // UB -- use after free; (3) Integer overflow (signed): int x = INT_MAX; x++; // UB! (unsigned overflow is defined -- wraps); (4) Uninitialized variable use: int x; std::cout << x; // UB -- garbage value; (5) Strict aliasing violation: accessing memory through a pointer of a different type: int i = 42; float* f = reinterpret_cast<float*>(&i); *f; // UB; (6) Data races: two threads access same non-atomic variable, one writes; (7) Shift by negative/overflow: int x = 1 << -1; // UB; 1 << 32 // UB on 32-bit; (8) Modifying a string literal; (9) Double-free: calling delete twice on the same pointer. Detection tools: AddressSanitizer (-fsanitize=address) — finds memory errors at runtime; UBSanitizer (-fsanitize=undefined) — detects signed overflow, null deref, OOB; ThreadSanitizer (-fsanitize=thread); Valgrind; static analyzers (clang-tidy, cppcheck). Avoidance: use smart pointers, std::vector/string (eliminate raw arrays), -Wall -Wextra flags, sanitizers in CI, code reviews, modern C++ idioms.

Common Mistake

Don't just define the term — demonstrate that you understand when to use it and when not to. Showing awareness of trade-offs is what separates average from strong C++ candidates.