4

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
            }
2
  • Is this a 32-bit process? What is your memory consumption like? Commented Mar 29, 2015 at 8:27
  • You should perhaps learn to avoid using for loops in c#. Commented Mar 29, 2015 at 13:26

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

6 Comments

also you (the OP) can use checked to check this ;)
So this works: List<byte> testlist = new List<byte>(); for (int i = 0; i <= 255; i++) { testlist.Add((byte)i); }
@CarstenKönig Ah, didn't know about checked. Would not want to use it explicitly everywhere though. ;)
@MickyDuncan of course there is a global compiler switch too ;)
this is super cool. I didnt work it out until I put console.writeline in and wondered why it was taking so long!!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.