Sreeraj
Sreeraj

Reputation: 21

How to overcome stack overflow exception in c# while calling a recursive function

I am doing a recursive program and during the execution of a recursive function it shows stack overflow error. I cannot proceed without completing this recursive function. Please some one help me... This is the code that i have done:

   public void blob(int k, int l, int[,] MV1)
    {
        while (true)
        {
            if ((MV1[k, l] == 1) && (status[k, l] != 1))
            {
                count = count + 1;
                if (count < 6000)
                {
                    if (k < xmin)
                    {
                        X[Xr, 0] = k;
                        xmin = k;
                    }
                    if (l < ymin)
                    {
                        Y[Yr, 0] = l;
                        ymin = l;
                    }
                    if (k > xmax)
                    {
                        X[Xr, 1] = k;
                        xmax = k;
                    }
                    if (l > ymax)
                    {
                        Y[Yr, 1] = l;
                        ymax = l;
                    }
                    status[k, l] = 1;


                    if (l != (MV1.Length / MV1.GetLength(0)) - 1)
                    {
                        blob(k, l + 1, MV1);
                    }
                    if ((l != 0))
                    {

                        blob(k, l - 1, MV1);

                    }
                    if (k != MV1.Length - 1)
                    {
                        blob(k + 1, l, MV1);
                    }
                    if ((k != 0))
                    {

                        blob(k - 1, l, MV1);

                    }

                }
            }

Upvotes: 1

Views: 254

Answers (1)

rory.ap
rory.ap

Reputation: 35270

The problem is your method never exits the while loop because you have while (true). Therefore, your recursive algorithm keeps calling itself deeper and deeper until it runs out of space on the stack.

You need to make it so your loop exits at some point, either from within using return or preferably with a better condition in your while statement.

Note, it's generally considered bad practice to use while (true). You want to avoid doing so unless absolutely necesssary.

Upvotes: 1

Related Questions