C/C++: feedback in analyzing a code example
Posted
by
KaiserJohaan
on Stack Overflow
See other posts from Stack Overflow
or by KaiserJohaan
Published on 2011-03-02T15:21:04Z
Indexed on
2011/03/02
15:24 UTC
Read the original article
Hit count: 281
Hello,
I have a piece of code from an assignment I am uncertain about. I feel confident that I know the answer, but I just want to double-check with the community incase there's something I forgot. The title is basically secure coding and the question is just 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 could imagine the code would run forever, considering it's initialized to a positive value and ever increasing. This of course is wrong because eventually the value will grow so large it will cause an integer overflow. This in turn is not entirely true either, because eventally it will force the variable 'i' to be signed by making the last bit to 1 and therefore regarded as a negative number, therefore terminating the loop. So it is not writing to unallocated memory and therefore cause integer overflow, but rather violating the data type and therefore causing the loop to terminate.
I am quite sure this is the reason, but I just want to double check. Any opinions?
© Stack Overflow or respective owner