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

>It's unclear to me why our languages still default to modulo arithmetic semantics.

Because that's what processors do? (leaving aside backwards compatibility issues)



Our processors also require manually manipulating registers.

The whole point of higher level programming languages is to abstract away the fiddly bits of dealing with processors that we don't want to have to deal with.

This is one of those cases.


In this case it's really that the cost of determining if an overflow did occur or will occur on modern architectures is too high and the likelihood too low for it to be reasonable to perform the checks in most cases in native code. Might be different for interpreted languages depending on a lot of things (whether or not they even use integer arithmetic, whether or not they default to some arbitrary precision integers by default, etc.). If common architectures automatically interrupted on overflow rather than setting a flag at no additional cost, I'd think you'd see safety guarantees instantly.


In cases where you're willing to take the perf hit, you can just use languages like Python which abstract over integer size entirely.


Which used to, but at least for parsing ints they've snuck in the perf hit as a "security vulnerability."


Processors also emit a signal when there's an over/underflow. Is it costly to check that at a low level and terminate the process in this case?


Saturated arithmetic instructions do not do this.


And on the platforms where the ADD instruction uses saturated arithmetic I bet assert(UINT32_MAX + 1 == UINT32_MAX) in C passes.


Unsigned integers in C are defined to wrap on overflow, so they shouldn't be affected by what the underlying processor wants to do. And just because signed overflows are undefined doesn't mean you get what the processor provides either.

So basically, don't forget to test with UBSan.

(I don't like -fno-strict-overflow as a solution, because defining incorrect behavior isn't much better than undefined behavior.)


TIL modulo wrapping for unsigned ints is actually in the standard, I could have sworn it was implementation defined (as opposed to signed wrapping, which is undefined).




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

Search: