<<
 
>>
 
 
justin = {main feed , music , code , askjf , pubkey };
 
signed overflow undefined behavior is real
April 26, 2025
We had an interesting crash recently, which involved some code like this:
  void foo(double v, char buf[1024]) {
    int iv = (int)v;
    int a = 100 + iv;
    if (a < 100) a = 100;
    for (int b = a; b < 1024; b ++)
    {
       buf[b] = 1; // crash here
    }
  }
(this is a manually-recreated code, the actual code had substantial differences). Assume buf points to a buffer that is valid and 1024 bytes long. what gives?

Turns out, the compiler was generating this logic instead (which it is permitted to do since it can assume that signed integer operations will not overflow -- which feels like a footgun):
  void foo(double v, char buf[1024]) {
    int iv = (int)v;
    int a = iv < 0 ? 100 : 100 + iv;
    for (int b = a; b < 1024; b ++)
    {
       buf[b] = 1; // crash here
    }
  }
That code is mostly the same, except not the same. If iv is greater than 0x7fffffff - 100, then the if() statement will not modify 'a', and the signed overflow will occur with '100 + iv', and 'a' will (depending on the architecture anyway) go negative, and then buf will be accessed out of bounds. Sigh.

Oh well, something to keep an eye out for. I'll be clamping my values in floating-point-space from now on...
Add comment:
Name:
Human?: (no or yes, patented anti crap stuff here)
Comment:
search : rss : recent comments : Copyright © 2025 Justin Frankel