|
|
Subscribe / Log in / New account

Footguns

Footguns

Posted Jul 15, 2021 10:14 UTC (Thu) by khim (subscriber, #9252)
In reply to: Footguns by cortana
Parent article: Rust for Linux redux

Yes, assert(x < INT_MAX - 100) is the one pushed by C compiler developers, but since unsigned overflow is not a thing (usigned arithmetic is defined as modular arithmetic by the standard thus it may never overflow)… and since conversion between signed and unsigned was always implementation-defined behavior, not undefined behavior… and since in C++ is mandatory to use two's complement now… starting from C++20 in theory and in all existing compilers in practice you can use… drumroll… assert((int)((unsigned)x + 100U) > x);. Easy, ne?

It works exactly the same as assert(x + 100 > x); (with -fwrapv) the only difference it that it's ugly and you wouldn't learn about it in books.

That's the problem with C/C++ compiler developers: it lies not with the fact that it's impossible to write correct C/C++ code. But it's hard, and, worst of all, C/C++ compiler developers employ extremely strong SEP field and never even consider the need, to, you know, write real program somehow, important. It's always “go read the standard”, “our way or the highway” style discussion.

And __builtin_add_overflow shows that perfectly: yes, it's very nice solution. The only issue: gcc 2.95 from last century already breaks these checks, yet first version of GCC which got __builtin_add_overflow was version 5.0 (and clang got that one even later and no because they think C developers deserve it, but because they wanted to be more GCC compatible).


to post comments

Footguns

Posted Jul 15, 2021 14:08 UTC (Thu) by cortana (subscriber, #24596) [Link]

Thanks. And wow that expression with the casts is unpleasant... I think I'll stick with the INT_MAX version!


Copyright © 2025, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds