|
|
Subscribe / Log in / New account

Better handling of integer wraparound in the kernel

Better handling of integer wraparound in the kernel

Posted Jan 29, 2024 2:09 UTC (Mon) by NYKevin (subscriber, #129325)
In reply to: Better handling of integer wraparound in the kernel by donald.buczek
Parent article: Better handling of integer wraparound in the kernel

INT_MAX - b overflows for all negative b, not just INT_MIN. The ideal way to do this is with the compiler intrinsics or stdchkdint.h (C23). If you insist on doing it with regular arithmetic, then a + b never overflows for positive a and negative b (or vice-versa), nor will overflow happen if either operand is zero, so you can write some godawful nested ternary expression to check for the four possible cases (both positive, both negative, signs differ, either operand is zero) and hope the compiler is smart enough to understand what you are doing.

But don't actually do that. Just use the intrinsic.


to post comments

Better handling of integer wraparound in the kernel

Posted Jan 29, 2024 6:29 UTC (Mon) by donald.buczek (subscriber, #112892) [Link]

> INT_MAX - b overflows for all negative b, not just INT_MIN

Correct. Thanks for pointing that out!

> But don't actually do that. Just use the intrinsic.

Agreed.


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