The production bug that made me care about undefined behavior
4 months ago
- #Undefined Behavior
- #Initialization
- #C++
- The author recounts a bug in a C++ codebase where an HTTP endpoint returned both 'error' and 'succeeded' as true, which should have been mutually exclusive.
- The issue stemmed from uninitialized boolean fields in a struct due to C++'s default initialization rules, leading to undefined behavior.
- The struct 'Response' had a non-POD type (std::string), triggering the compiler to generate a default constructor that didn't initialize primitive fields (bool).
- Solutions included implementing a default constructor, setting default values in the struct definition, or using zero initialization at declaration (Response response{}).
- Tools like Address Sanitizer (ASan) and clang-tidy can detect such issues, but require comprehensive test coverage and have performance costs.
- The author highlights the complexity and pitfalls of C++ initialization rules, contrasting them with simpler approaches in languages like C, Go, and Rust.
- The post emphasizes the real-world dangers of undefined behavior, which can cause programs to behave unpredictably despite seemingly correct code.