Everything in C is undefined behavior

· coding · Source ↗

TLDR

  • A 30-year C/C++ veteran argues that all nontrivial C/C++ code contains undefined behavior, with the C23 standard listing 283 explicit UB instances.

Key Takeaways

  • UB is not about compiler optimizations; the compiler assumes code is valid and has no obligation to handle cases the standard leaves undefined.
  • Common UB traps beyond memory safety: unaligned pointer casts, isxdigit() on signed char, float-to-int conversion for non-finite values, and printf format mismatches.
  • memset(&ptr, 0, sizeof(ptr)) does not guarantee a NULL pointer; the C abstract machine does not require NULL to equal address zero.
  • LLMs can reliably spot UB in mature codebases – the author used one to find an out-of-bounds write in OpenBSD’s find.
  • Integer promotion rules (e.g., unsigned char arithmetic silently widening) produce counter-intuitive results that almost no one catches at code-review speed.

Hacker News Comment Review

  • No substantive HN discussion yet.

Original | Discuss on HN