Habil Ganbarli
Habil Ganbarli

Reputation: 223

C Recursion segmentation fault

I am new to C and trying to do a maze problem where 0 and letters are passing points and 1 is a barrier.

My 2D maze array are below where the starting point is at(0,4) and every time I have to check for 4 directions (N,S,E,W), and I have also the path array (initially contains "0" as chars) where I will put the routes as "R" which is also the same size:

1111S11110       
0000010001
110100010d
t001111110
0100000001
0111111101
1111111101
00000D01T1
0111110001
0000E01110

I am using recursive solution for pathfinding and in total use 3 functions which are below:

int isSafe(char Mazearray[matrixSize][matrixSize],int x,int y){
    if(x >= 0 && x < matrixSize && y >= 0 && y < matrixSize && Mazearray[x][y] != '1'){
        return 1;
    }
    return 0;


}

void MazeSolution(char Mazearray[matrixSize][matrixSize],int x,int y,char pathArray[matrixSize][matrixSize]){
    if(recursiveMaze(Mazearray,x,y,pathArray) == 0){
        printf("There does not exist a possible solution!!!");
    }
    else{
        int i,j;
        for (i = 0; i < matrixSize; ++i){
            for (j = 0; j < matrixSize; ++j){
                printf("%c",pathArray[i][j]);
            }
        printf("\n");
        }
    }
}

int recursiveMaze(char Mazearray[matrixSize][matrixSize],int x,int y,char pathArray[matrixSize][matrixSize]){
    if(x == exitX && y == exitY){
        pathArray[x][y] == 'E';
        return 1;
    }
    // check if the coordinate is safe to go(not 1)
    if(isSafe(Mazearray,x,y) == 1){
        pathArray[x][y] == 'R';
        // Move North
        if(recursiveMaze(Mazearray,x-1,y,pathArray) == 1){
            return 1;
        }
        // Move South
        if(recursiveMaze(Mazearray,x+1,y,pathArray) == 1){
            return 1;
        }
        // Move East
        if(recursiveMaze(Mazearray,x,y+1,pathArray) == 1){
            return 1;
        }
        // Move West
        if(recursiveMaze(Mazearray,x-1,y-1,pathArray) == 1){
            return 1;
        }
        pathArray[x][y] == '0';
        return 0;
    }
    return 0;
}

When I run the MazeSolution(), the program terminates with error code 255 and segmentation fault. When I debugged the problem appears at recursiveMaze() function.

So that, starting from first if statement it does not execute and the other problem is it goes and comes back between south and north control points.

Upvotes: 2

Views: 99

Answers (1)

jxh
jxh

Reputation: 70412

Here is a call sequence that leads to an infinite loop:

recursiveMaze(M, x, y, p)
   recursiveMaze(M, x-1, y, p)
       recursiveMaze(M, x-1, y, p) -> run to completion
       recursiveMaze(M, x+1, y, p) -> infinite loop

It is infinite because in the second recursive call, you increment back the value that had been decremented in the first recursive call, which takes you back to the same state as the initial call.

Upvotes: 3

Related Questions