Simple while loop

Soldato
Joined
9 Dec 2004
Posts
5,700
Location
Dorset
I've got a simple while loop in C;

int i=1
while (i>0)
{
i=i*1000
}

In theory this should never end, but it does (because i becomes too big). What causes that? I presume this is a computing basic (i.e; "cant handle a number over XXX), but I'm not entirely sure.

Thanks.
 
"It appears that this will go on forever, but in fact the value of i will eventually reach the maximum value storable in an unsigned int and adding 1 to that number will wrap-around to 0, breaking the loop. The actual limit of i depends on the details of the system and compiler used. With arbitrary-precision arithmetic, this loop would continue until the computer's memory could no longer contain i."

Quoted from wiki :)

http://en.wikipedia.org/wiki/Infinite_loop
 
Last edited:
and .NET would throw a numeric overflow exception

no coder worth his salt would be writing code like that anyway.

It looks to me like a snippet of code designed to test your knowledge of the maximum values that you can store store in an int type. In C this is platform dependent and is defined in one of the header files on most other systems (.NET, Java etc) it's fixed and predefined.

HT
 
It looks to me like a snippet of code designed to test your knowledge of the maximum values that you can store store in an int type.

Exactly that, we're looking at code vulnerabilities. Thanks for your input guys.
 
FirebarUK said:
I've got a simple while loop in C;

int i=1
while (i>0)
{
i=i*1000
}

In theory this should never end, but it does (because i becomes too big). What causes that? I presume this is a computing basic (i.e; "cant handle a number over XXX), but I'm not entirely sure.

Thanks.

Its pretty simple to be honest, int is signed so it overflows and become negative thus terminating the loop. (over 2^31 + 1 it will wrap round to -2^31 - (Assuming 32bit ints - sizeof(int)))

http://en.wikipedia.org/wiki/Integer_overflow

Its actually quite common, and in some situations you can exploit it to cause arbitary random code execution.

If you want more info search phrack 60 - Webby is currently down atm, but google cache has it.
 
Last edited:
Una said:
Its pretty simple to be honest, int is signed so it overflows and become negative thus terminating the loop. (over 2^31 + 1 it will wrap round to -2^31 - (Assuming 32bit ints - sizeof(int)))
To be pedantic, 2^31-1 is the largest value representable as a signed 32 bit int.
 
DaveF said:
To be pedantic, 2^31-1 is the largest value representable as a signed 32 bit int.

And as default int is signed it would say unsigned int if it wasn't :p
 
Back
Top Bottom