Feedback on sample code analysis (secure coding)

I have a piece of code from a job that I'm not sure about. I feel confident that I know the answer, but I just want to double check with the community that there I forgot something. The name is basically safe coding, and the question is only to explain the results.

int main() {
   unsigned int i = 1;
   unsigned int c = 1;
   while (i > 0) {
     i = i*2;
     c++;
   }
   printf("%d\n", c);
   return 0;
}

My reasoning is this:

At first glance, you can imagine that the code will work forever, given that it is initialized with a positive value and is constantly growing. This, of course, is wrong, because in the end the value will be so great that it will lead to overflow of integers. This, in turn, is also not entirely true, because ultimately it will cause the variable "i" to sign, making the last bit equal to 1 and, therefore, be considered a negative number, so the loop ends. Thus, it does not write to unallocated memory and, therefore, causes an integer overflow, but rather violates the data type and, therefore, leads to the end of the cycle.

I am sure this is the reason, but I just want to double check. Any opinions?

+5
7

, unsigned int . - .

, 2 ( ) , , ( ), " " .

+5

. (UINT_MAX + 1).

, , , , 2, ...

, , unsigned 4 .

1 * 2 = 2 ==> 0b0010
2 * 2 = 4 ==> 0b0100
4 * 2 = 8 ==> 0b1000
8 * 2 = 0 ==> 0b0000
+2

; , , .

+1

signed integer, , , , -2147483648 2147483647. , .

unsigned integer, . , , , 0 4294967295.

, i=1; i = i*2;, , :

1 // 1 in base 10
10 // 2 in base 10
100 // 4 in base 10
1000
10000
100000
1000000
10000000
100000000
1000000000
10000000000
100000000000
1000000000000
10000000000000
100000000000000
1000000000000000
10000000000000000
100000000000000000
1000000000000000000
10000000000000000000
100000000000000000000
1000000000000000000000
10000000000000000000000
100000000000000000000000
1000000000000000000000000
10000000000000000000000000
100000000000000000000000000
1000000000000000000000000000
10000000000000000000000000000
100000000000000000000000000000
1000000000000000000000000000000 // 1073741824 in base 10
10000000000000000000000000000000 // 2147483648 in base 10 

, : while (i > 0) { i , , , 0. , - .

, i ( ), c=32 10000000000000000000000000000000 -2147483648 < 0. , , .

, , , , - . , , , , .

, , Java . , . .

+1

i . - ( , ) 0, .

0

, int - ( , , , unsigned int 0), 0, , (- 2 ** 31 32- , )

0

Since I am an unsigned integer (0 - 255), I will be 0 after 8 iterations due to binary rounding.

0
source

All Articles