Brian
Brian

Reputation: 2108

StackoverflowException when filling array

I usually spend my time reading and trying to answer the Excel VBA questions but I am trying to learn C# now. Can someone help me understand why I get a StackOverflowException error on the second to last line in my code?
I am trying to fill an array via a method.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = GenerateNumbers();
            Console.WriteLine(numbers);
            Console.ReadKey();
        }
        static int[] GenerateNumbers()
        {
            int[] num = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            return GenerateNumbers();
        }
    }
}

Upvotes: 4

Views: 396

Answers (4)

Twahanz
Twahanz

Reputation: 224

A stack overflow is an undesirable condition in which a particular computer program tries to use more memory space than the call stack has available. In programming, the call stack is a buffer that stores requests that need to be handled. http://whatis.techtarget.com/definition/stack-overflow

 static int[] GenerateNumbers()
 {
     int[] num = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
     return GenerateNumbers(); //Here is where the problem happens
 }

The problem lies with the return part. You are calling the same function in the same function creating a stack of the same function again and again and... You get the picture.

Change it to

return num;

Upvotes: 5

Rytis I
Rytis I

Reputation: 1303

This is what you're esentially doing:

void Main() 
{
    FlipPage();
}

void FlipPage()
{
    FlipPage();
}

So like that blond you keep flipping that page in all eternity

Upvotes: 0

Andrew
Andrew

Reputation: 388

By calling return GenerateNumbers() at the end of your function, you are running that function over and over again infinitely because there is no way to break the recursion, causing the stack overflow. You should instead use return num

Upvotes: 0

Camilo Terevinto
Camilo Terevinto

Reputation: 32068

You are confusing the weird VBA way of returning functions with C#. You are returning an infinite recursion, which can be easily fixed by using this:

    static int[] GenerateNumbers()
    {
        int[] num = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        return num; //you don't return the function name but a variable
    }

Upvotes: 10

Related Questions