So, the question is, when you know an integer is not going to be negative, is that
good enough reason to declare it as unsigned
Yes.
Several critical security vulnerabilites have been discovered in the
last year or so that have been caused by integer manipulation issues.
These have occurred not only in Microsoft software(the latest ASN.1
critical vulnerability is one example), but in several open source
software packages and closed source packages from other vendors.
The contents of this thread suggests that, even amongst experienced C
programmers, there is still a disturbing lack of awareness of this
issue.
If you have any doubt on the seriousness of integer manipulation bugs
follow this link:
http://www.google.com/search?q=integer+overflow
I suggest every C\C++ programmer starts by reading these articles:
http://msdn.microsoft.com/library/en-us/dncode/html/secure04102003.asp
http://msdn.microsoft.com/library/en-us/dncode/html/secure09112003.asp
As an exercise consider the additional checks that need to be taken in
the check() function below. How many would be removed by making a and
b unsigned?
int check(signed int a, signed int b)
{
/* a and b are considered untrusted numbers. */
if (a + b < 50)
return 1;
else
return 0;
}
void somefunc(void)
{
/* a_cnt, b_cnt, a_str, b_str from somewhere */
char buf[50];
if (!check(a_cnt, b_cnt) return;
strncpy(buf, a_str, a_cnt);
strncpy(buf, b_str, b_cnt);
}