by pslam · 13y ago · 0 comments
I think most languages would benefit from unsigned types being the default, and arithmetic overflow being a hard error unless otherwise decorated. Signedness and lenient overflow promote laziness. Array indexes don't make sense as signed, yet most people prefer to iterate arrays with a signed type, e.g most commonly:
for (int i = 0; i < 10; ++i) buf[i] = 0;
Far too many people rely on signed integer overflow working as you expect the underlying machine to handle it - but that's not what the C spec says and not how a compiler handles it either.There are countless security issues I've had to fix related to signed types in what is supposed to be secure code. These would not have occurred if the author was forced to use an unsigned type, and had to consider the extreme limits of the values it can take on. Subtle things such as the addressable limit of memory being naturally unsigned, but buffer sizes being passed as signed, can cause easy exploits, and are stupidly commonplace.
Most commonly you'll actually want to go positive, and have an array going from a[1970] to a[2013] or something similar.
int array[FOO];
int *shifted_array = array + FOO/2;EDIT: just tried it. The following works:
#include <stdio.h>
int main(void)
{
int array[100];
int *shifted_array = array - 1980;
for (int i = 0; i < 100; i++)
array[i] = i;
for (int j = 1980; j < 2014; j++)
printf("shifted_array[%d] = %d\n", j, shifted_array[j]);
return 0;
} unsigned int i = strlen(s) - 1;
for (; i >= 0; --i) { // BUGBUG
if (s[i] == '.') {
break;
}
}
(Yes, you can make it work, but it is very error-prone when people try). for (unsigned i = strlen(s); i > 0; --i) {
if (s[i - 1] == '.') break;
}
Easy to see that s[i-1] does not underflow the array due to the loop invariant i>0. It's usually easy to convert signed iteration code to unsigned and when I see this, I can tell the author spent the time to consider what happens at the limits of their inputs.Some errors are more subtle and not flagged by compilers, but many are.