Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The compiler can't warn about something like this? I guess unsigned integer underflow can be the intended behavior often.


It could, for other reasons, never underflow. C expects that you know what you're doing, and C expected you did a bounds check. But I agree. Cases like this should have a lint warn on them, saying -- "Wake up programmer!"


Fundamentally this problem cannot be solved at the compile-time level because, well, code is dealing with the values which are only known during code execution runtime. So I don't think compiler can do much here other than providing you with a hint that you may rewrite your expression but only to reduce the risk of a potential error, e.g. `if (len + 2 + size > PAGE_SIZE)` still still remains feasible to unsigned integer overflow and to handle the problem fully one must either:

1. Write a lot of convoluted if..else logic such as https://wiki.sei.cmu.edu/confluence/display/c/INT30-C.+Ensur... and https://wiki.sei.cmu.edu/confluence/display/c/INT32-C.+Ensur...

2. Or use compiler built-in intrinsics, e.g. https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins...

But almost nobody does that ... except probably where it really matters (not the OS kernel).


A dynamic_assert() function would be a more general way to check a predicate at runtime. It can be compiled out for release builds and report failures to a centralized log for cases where the assertion is ignored.


Yeah, I mean that's just a normal `assert()` from <assert.h> and it doesn't solve the problem because nobody runs debug builds in production neither it is possible in a reasonably complex software predict in what ways your users are going to be using it and therefore cause bugs you'd never have imagined that could happen.

But speaking of asserts, there could be a runtime assert but which is also _kept_ in release builds. On detection of invariant not being valid, it would just crash the program. That approach works for some fields in engineering but not so much in others however it could be considered as an alternative.


What you say makes sense. I was obviously wishcasting. ;)


Not solved at compile-time, but warned at compile time?


Warned about what exactly? Literally any operation on two unsigned integers can either underflow or overflow and any of those would still be correct and expected behavior.


Could be solved at compile time with proof of absence of runtime errors, which somehow forces you to handle all cases for any input.


It's not obvious what the warning would be, unless you want a warning attached to every single arithmetic operation? The compiler can't know what `size` will be in this case.


Comparisons in an if statement involving subtracting two unsigned variables from each other?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: