HeadlinesBriefing favicon HeadlinesBriefing.com

C/C++ Undefined Behavior Makes Correct Code Impossible

Hacker News •
×

A veteran developer with 30 years of C/C++ experience argues that undefined behavior (UB) permeates all nontrivial code, making truly correct programming impossible. Despite knowing common pitfalls like double-free errors, the industry repeatedly makes these mistakes. The author contends that even careful code contains subtle UB that compilers and hardware interpret differently, turning obvious intentions into unverifiable assumptions.

Many believe UB only triggers with optimizations enabled, but this is false. UB means the compiler assumes your code is valid, potentially omitting necessary safety checks. Examples include misaligned pointer accesses: while x86 may handle them gracefully, architectures like SPARC can crash with a SIGBUS, and future designs might behave differently. The compiler isn't obligated to generate safe code for such cases because it's UB.

Specific examples abound. Casting a `char` to `int` for `isxdigit()` can cause out-of-bounds reads if `char` is signed. Converting a `float` to `int` risks UB from overflow or non-finite values, requiring complex checks for a simple operation. Even placing an object at address zero lacks a standards-compliant method. The author recalls a prominent claim that using C++ could constitute a SOX violation, a point they find increasingly valid under the C23 standard.

This isn't about programmer error but language design. If undefined behavior is unavoidable, blaming developers is unjust. The environment has changed since C's 1972 debut or C++'s 1985 arrival, yet these languages remain foundational, creating a growing reliability chasm.