1

So this is my code:

static void Main(string[] args)
{
    Console.WriteLine("How many numbers are you going to enter?");

    long num = long.Parse(Console.ReadLine());

    long[] nums = new long[num];
}

When I enter 10000000000 for "num" I get

"System.OverflowException Arithmetic operation resulted in an overflow."

What do i do to fix it?

3
  • 1
    I'd start by catching it. Commented Dec 31, 2015 at 15:32
  • This is some 80 GB of memory. Only 64-bit processes can handle this. Commented Dec 31, 2015 at 15:33
  • 1
    The number you are trying to use goes above Int32.MaxValue and you cannot create an array that big. Commented Dec 31, 2015 at 15:33

2 Answers 2

9

Your code overflows because the maximum size for an array in C# is Int32.MaxValue, which equals to 2147483647. You can see hints to that in the source code, and it is clearly stated in the documentation:

By default, the maximum size of an Array is 2 gigabytes (GB). In a 64-bit environment, you can avoid the size restriction by setting the enabled attribute of the configuration element (<gcAllowVeryLargeObjects> introduced in .NET 4.5) to true in the run-time environment. However, the array will still be limited to a total of 4 billion elements, and to a maximum index of 0X7FEFFFFF (2146435071) in any given dimension (0X7FFFFFC7 (2147483591) for byte arrays and arrays of single-byte structures).

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

Comments

4

Okay, you are trying to allocate a lot of memory, since calling the long array constructor, actually already frees the memory you requested. A long is 64 bits, so 8 bytes. 8 bytes * 10000000000 = 80 GB of memory. That's too much.

The maximum length of an array in C# is int.MaxValue, which is 2,147,483,647 (16GB using a long), assuming you have enough memory.

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.