4 ms·
The advantage of using signed types is that you can reliably find overflow bugs using UBSan and protect against exploiting such errors by trapping at run time.
by uecker 3y ago
The advantage of using signed types is that you can reliably find overflow bugs using UBSan and protect against exploiting such errors by trapping at run time. For unsigned types, wrap-around bugs are much harder to find and your program will silently misbehave.
- harpiee 3y agoWith unsigned you can actually check for overflow yourself very easily z=x+y; if(z < x || z < y) // overflow And bounds checks are just a single comparisons against an upper bound (handles both over and underflow) size = x + y; // or size = x - y if(size < bound) // good to go Prior to C23 (stdckdint.h) its very error prone to check for signed overflow since you have to rearrange equations to make sure no operation could ever possibly overflow.
- uecker 3y agoYou can write correct programs with both. The reality is that people often fail to do this. But you can automatically detect signed overflow and protect against it, while unsigned wrap detected at run-time could be a bug or could be just fine (e.g. because you did your own "overflow" check and handle it correctly). This makes it extremely hard to find unsigned wraparound bugs and impossible to trap at run-time.