I'm getting an out of memory exception and I don't know why? This is a my C# code:
List<byte> testlist = new List<byte>();
for (byte i = 0; i <= 255; i++)
{
testlist.Add(i); //exception thrown here in the last cycle
}
Your loop never terminates because byte
is an unsigned, 8-bit integer with valid values between 0 and 255.
So, when i == 255
and the loop body completes, another increment occurs. However, due to the range of byte
, this does not cause i
to equal 256
(it can't!), which would in turn cause the loop to terminate. Instead, it overflows, and rolls around to 0
. So, the loop goes on (and on and on...). This is a relatively common bug when using unsigned loop counters.
In the meantime, your list is growing until you run OOM. There's no reason to use a byte
here; just use int
and cast i
when adding it to the list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With