- Home /
Stack Overflow in if condition.
I have the following code where i try to recursively call a function:
if( value == 1 ) function();
I tested and the value is not always 1 but i get a StackOverflow error when running. I can't seem to find the problem. I could use some help solving this.
Thanks in advance.
Edit:
private void AddNeighbors( Vector2 o, Vector2 s )
{
//Debug.Log( "Called" + o );
int notAdded = 0;
// LEFT //
int[ , ] left = GetRoom();
int leftZeroCount = 0;
for( int x = 0; x < left.GetLength( 0 ); ++x )
{
float a = o.x - left.GetLength( 0 ) + x;
for( int y = 0; y < left.GetLength( 1 ); ++y )
{
float b = o.y + y;
if( a > 0 && b > 0 && grid[ ( int )a, ( int )b ] == 0 )
++leftZeroCount;
}
}
if( leftZeroCount == left.GetLength( 0 ) * left.GetLength( 1 ) )
{
int add = Random.Range( 0, 2 );
if( add == 1 )
{
Vector2 origin = new Vector2( o.x - left.GetLength( 0 ), o.y );
for( int x = 0; x < left.GetLength( 0 ); ++x )
{
float a = origin.x + x;
for( int y = 0; y < left.GetLength( 1 ); ++y )
{
float b = origin.y + y;
grid[ ( int )a, ( int )b ] = left[ x, y ];
}
}
AddNeighbors(
origin,
new Vector2( left.GetLength( 0 ), left.GetLength( 1 ) )
);
}
else ++notAdded;
}
else ++notAdded;
// CHECK IF ADDED //
if( notAdded == 1 ) AddNeighbors( o, s );
}
The GetRoom function returns an random int[ , ] composed of ones and zeros.
To troubleshoot your issue we'll need more information. Could you link the rest of your scrip?
For recursives there must be something inside function() that changes value(). Is there?
Please post the entire script for function ()
Answer by tanoshimi · Jul 20, 2014 at 10:53 AM
As far as I read it, the possible paths through your function are as follows:
leftZeroCount == left.GetLength( 0 ) * left.GetLength( 1 )
(line 19) is true, andadd == 1
(line 22) is true, in which case you call AddNeighbors again (line 34).leftZeroCount == left.GetLength( 0 ) * left.GetLength( 1 )
(line 19) is true, andadd == 1
(line 22) is false, in which case you++notAdded;
(line 39).leftZeroCount == left.GetLength( 0 ) * left.GetLength( 1 )
(line 19) is false, in which case you++notAdded;
(line 41).
If either of the last two cases happens, then notAdded == 1
, in which case you call AddNeighbors again (line 44)
So, whatever happens, this is an endless recursive loop, which is why you're getting a stack overflow.
Thank's a lot the outside else statement didn't need to be there it work's perfectly now.
Your answer
Follow this Question
Related Questions
Huge Lists cause unity to throw bug reporter and crash? 0 Answers
Recursing through a bone hierarchy: Stack Overflow 1 Answer
Stack overflow with recursive floodfill method. 2 Answers
I'm getting StackOverFlowException 1 Answer
A better way to write a recursive if statement like this mess? 0 Answers