3 ms·
> int8(100) + int8(100) = -56 is just one possible answer. Signed integer overflow depends on signed integer representation in go (it's undefined for unsigned
by legulere 11y ago
> int8(100) + int8(100) = -56
is just one possible answer. Signed integer overflow depends on signed integer representation in go (it's undefined for unsigned integers in C):
https://golang.org/ref/spec#Integer_overflow https://golang.org/ref/spec#Integer_overflow
So the SafeAddInt8 in the blogpost may not be correct on architectures that use really strange representations.
Lots of C developers that wanted to make their code safer ran into a related trap in C. There it's totally undefined and the compiler may just throw the check out all together.
I wonder why Go doesn't just define signed integers to be in 2's complement representation. Are there any architectures out there that use something else for integers?
- agwa 11y ago> (it's undefined for unsigned integers in C): No, unsigned integer overflow is defined to wrap around in C. Only signed integer overflow is undefined. > I wonder why Go doesn't just define signed integers to be in 2's complement representation It does: "The value of an n-bit integer is n bits wide and represented using two's complement arithmetic" (from https://golang.org/ref/spec#Numeric_types https://golang.org/ref/spec#Numeric_types)
- legulere 11y agoYou're right, I wanted to write signed integers. I wonder what they mean with representation in the spec then?
- spc476 11y agoMore so, using 'JO' (jump overflow) after every signed operation isn't that expensive, speedwise (branch prediction for the win) but it does make the code larger. http://boston.conman.org/2015/09/07.1 http://boston.conman.org/2015/09/07.1
- GeorgeTirebiter 11y agoWouldn't this sort of thing be better handled by an exception? The CPU should help us more to write better secure software.
- spc476 11y agoIt would, but the x86 doesn't trap on signed overflow. There is an INTO instruction (interrupt on signed overflow) but you have to include it after every signed instruction, and when I tested that, it was apparent that INTO is not a "fast instruction". Also, under Linux, when INTO fires, it is interpreted as a SIGSEGV. Not what I was expecting.