Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OutOfMemoryException when filling List<byte> in C#

Tags:

c#

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
            }
like image 495
user3557176 Avatar asked Dec 19 '22 05:12

user3557176


1 Answers

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.

like image 105
Ed S. Avatar answered Jan 09 '23 06:01

Ed S.