Attention people who think UB is fine
This technical article explores the dangers of undefined behavior (UB) in C and C++ programming. It demonstrates how compiler optimizations can lead to unexpected and potentially dangerous code execution when developers rely on assumptions about memory access.
Why it matters
Understanding undefined behavior is critical for systems programming and security, as incorrect assumptions can lead to critical software vulnerabilities.
After my post on undefined behavior in C some people insisted that it’s demonstrably fine, we know what the code will do, and at worst we’ll get a segfault.
#include<utility> // Let's pretend this is a memory mapped device controlling // motors and gears and stuff. volatile int device_command = 0 ; void serve_hot_chocolate () { device_command = 42 ; // Oh no, we spilled some hot chocolate, invoking UB. // // The definition of `std::unreachable()` is: // Invokes undefined behavior at a given point. std :: unreachable (); } void explode () { device_command = 3 ; } Example assembly output With GCC 16.2 with -O1 .
"serve_hot_chocolate()" : mov DWORD PTR "device_command" [rip], 42 "explode()" : mov DWORD PTR "device_command" [rip], 3 ret "device_command" : . zero 4 Ruh roh. Exploding chocolate! The function explode() will be executed, even though it was never called!
Get smarter about the news
Sign up free for a feed built around what you actually care about, Dive Deeper research on any story, and the full text of every article.
Create free accountAlready have an account? Sign in