Lobste.rs

Attention people who think UB is fine

Season 3 - Meta Insights: Part 2 : r/Competitiveoverwatch

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. This is false. Here’s an example. C code #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…

Continue reading at Lobste.rs blog.habets.se
Advertisement