Check for unsigned zero

Playing with some sources of the found code as follows:

void foo(unsigned int i) { if(i<0) printf("Less then zero\n"); else printf("greater or equ\n"); } int main() { int bar = -2; foo(bar); return 0; } 

I think it makes no sense, but can there be some cases (security?) That make this check sensitive?

+4
source share
2 answers

An unsigned int cannot be less than 0 by definition. Therefore, in order to more accurately answer your question, you are right in thinking that this makes no sense. This is not a significant security element unless you come across something like a loop that accidentally reduces the signed int to the past 0, and then outputs it as an unsigned int for use as an index into an array and, therefore, indexes memory outside the array.

+13
source

i will always be >=0 because it is declared as unsigned and therefore interpreted as an unsigned integer. So your first test will always be false.

Your call to foo(bar) actually convert int to unsigned int . Perhaps this confuses you. And the "conversion" does not actually change the value of the bytes / bits of your whole, it is just a matter of formal typing and interpretation.

See this answer for examples of signed / unsigned conversions.

Here is a simple example (the exact output depends on the number of bytes of unsigned int in your system, for me it is 4 bytes).

the code:

 printf("%u\n", (unsigned int) -2); 

Conclusion:

 4294967294 
+2
source

All Articles