1

I am receiving an error on my C# Console Application. I am trying to do some code but its throwing an exception whenever I do so, not all the time just some of the time, by the way it is not just me using this program there is 30+ members on it using it also.

Code:

int MessageLength = Base64Encoding.DecodeInt32(new byte[] { data[pos++], data[pos++], data[pos++] });
int MessageId = Base64Encoding.DecodeInt32(new byte[] { data[pos++], data[pos++] });

byte[] Content = new byte[MessageLength - 2];

The Exception is:

Exception logged 1/23/2015 10:54:54 AM in packet handling: System.OverflowException: Arithmetic operation resulted in an overflow.

The exception is happening on line 37, the following line...

byte[] Content = new byte[MessageLength - 2];

Here is a image of the lengths changing of 'pos' and 'MessgaeLength'

3
  • What is the value of MessageLength? Commented Jan 23, 2015 at 11:04
  • And the value from pos? Commented Jan 23, 2015 at 11:05
  • I will run some code to check, ill reply with the length in 2 minutes. Commented Jan 23, 2015 at 11:06

2 Answers 2

3

Make sure MessageLength > 2.

For example :

if (MessageLength < 3)
    throw new Exception("Incorrect MessageLength");

Otherwise, you are trying to instantiate an array with Length 0 / -X.

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

2 Comments

0 is an ok value, it might not be logical in this context, but you can certainly construct an array with a length of 0 in .NET.
I choose this method and it has stopped the exceptions so far, thank you.
1

The problem is most probably in the length of MessageLength. If the length is less than 2, you will get an overflow.

Try this failing code:

int x = 0;
byte[] Content = new byte[x - 2];

You should check before allocating that x-2 is more than or equals to 0:

if (MessageLength >= 2)
{
    byte[] Content = new byte[MessageLength - 2];

    ...
}

Comments

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.