3 ms·
Ah yes, integer overflow checking. Here's iDrive, the commercial backup service, failing at it: http://s24.postimg.org/xakc6eglx/idrivefail2.png http://s24.po
by Animats 12y ago
Ah yes, integer overflow checking. Here's iDrive, the commercial backup service, failing at it:
http://s24.postimg.org/xakc6eglx/idrivefail2.png http://s24.postimg.org/xakc6eglx/idrivefail2.png
iDrive backed up a 3GB file. This overflowed a 32-bit value, and so iDrive shows the size as -149406.91 KB. This seems to have confused something in the iDrive system, and now backups won't run. Their tech support people have been working on this for two days now.
C officially considers unsigned integer overflow to be modular arithmetic. I consider that a mistake. If you want modular arithmetic, you should write
x += n % (2^32)
which can be easily optimized to eliminate the divide. Otherwise, it should be an error.
- TazeTSchnitzel 12y agoMore portable: x += n % (1 << (SIZEOF_LONG * CHAR_BIT));
- jevinskie 12y agoPerhaps the C++ standard could add 'operator{+,-,etc}%'.
- TazeTSchnitzel 12y agoAlong the lines of Swift's & operators?
- jevinskie 12y agoYes, those seem quite nice! Edit: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html https://developer.apple.com/library/ios/documentation/Swift/...
- Animats 12y agoIf the program wants 32-bit unsigned modular arithmetic, that's what you should get, regardless of the underlying machine architecture. If you code that, you're probably doing a checksum, and you want the answer to be consistent across platforms.
- Someone 12y agoI don't think SIZEOF_LONG is portable C. You would want sizeof(long) * CHAR_BIT instead (while at it, use sizeof(x) instead, ?and abort if sizeof(n) > sizeof(x)?)). More importantly, I think that expression produces an int value, so if sizeof(long) > sizeof(int), that shift will produce undefined behaviour (or zero? I don't have a C standard to check that on at hand. Actually, shifting any integral type by its size in bits could well be undefined behavior) Even if that weren't the case, that doesn't do modular arithmetic. You would want x = (x + n) % (1 << (SIZEOF_LONG * CHAR_BIT)); and of course, that computes x+n before doing the modulus, so even that doesn't do modular arithmetic. I think one would need custom syntax for making modular arithmetic easy in C. I would suggest something like x += n (mod 37); That may make parsing difficult, though, if one allows expressions after the 'mod'. Alternatively, put the 'do modular arithmetic' thing in the type: modular(43) int x; modular(23) int y; int n = x + y; // error? Summary: this is way harder than it seems. I bet people will find errors in the above that show that conclusively. Edit: yes, it is harder. According to http://blog.regehr.org/archives/738 http://blog.regehr.org/archives/738, left-shifting a signed integer by one bit already can trigger undefined behaviour.