Search code examples
cmaze

Strange order of flow of control


I have been assigned to code a 'maze' program which will allow user to play and solve a random maze by navigating from start to end. So far I've developed a working prototype that runs well for predefined mazes, but the institution requires me to make it as random as possible. For that I included a function 'findpath' that check and verifies if the random maze can be solved or otherwise call 'mazebuilder' to create another random maze. The whole code is here : http://codepad.org/wb1OGGrZ . Now while execution, this function shows illegal flow of control.

int findpath(int x, int y)
{
    if(fpmap[x][y]==END)    //1
    {
        return TRUE;
    }
    if(fpmap[x][y]!=PATH||fpmap[x][y]!=START)     //2
    {
        return FALSE;      //2a
    }
    min_moves++;                    //3
    fpmoves++;
    fpmap[x][y]=SOLUTION;
    if(findpath(x,y-1))      //4
    {
        return TRUE;
    }
    if(findpath(x+1,y))
    {
        return TRUE;
    }
    if(findpath(x,y+1))
    {
        return TRUE;
    }
    if(findpath(x-1,y))
    {
        return TRUE;
    }
    min_moves--;      //5
    fpmap[x][y]=PATH;
    return FALSE;     //6
}

I tried to trace the program and this is what the function does upon its call : 1. Checks if #1. 2. Checks if #2. 3. Skips to #6. So, why didn't the program go to #2a or #3 if's after #4 or #5? It just seems to skip whole code and rush to #6. Is there a logical error in this or is this syntactical? Please help me out of this. PS: This code has been written for TurboC compiler because my faculties require me to do so. Please bear with me :(

More info on the algorithm used in findpath : http://www.cs.bu.edu/teaching/alg/maze


Solution

  • Compilers are strange beasts sometimes. The best explanation I can offer (as I see no direct coding erors that can cause your problem) is that the compiler has identified you are introducing undefined behavior and simply refused to compile the offending code (you can check this by inspecting the assembler code generated in a debugger).

    The offending code is that you do not check on the bounds of x and y before recursively calling findpath. The recursion can lead to x and/or y becoming smaller than zero or larger than scr+1.

    N.B.: also in mazeloader you have unneceasry recursion that will eventually lead to a stack overflow: if(findpath(start.x,start.y))...else goto top; instead of else mazeloader(); or even better, separate mazeloader form the user playing.