Home > OS >  SEGMENTATION FAULT for my code , need guidance with debugging
SEGMENTATION FAULT for my code , need guidance with debugging

Time:07-12

I am using the below code to solve the rat maze problem from geeksforgeeks.However I am getting the segmentation error and I am unable to debug it.Can someone guide me with the debugging? Here's the code:

class Solution{
    public:
    string x="";
    void rat(vector<vector<int>>&m,int n,vector<string>&ans,int i,int j)
    {
        cout<<"cool";
        if(i==n-1&&j==n-1)
        {ans.push_back(x);
        return;}
        
        if(m[i][j]==0)
        return;
       
        
        if(i<0||j<0||i==n||j==n)
        return ;
    
        if(i<n-1)
        {
            x ="D";
            rat(m,n,ans,i 1,j);
        }
        x.pop_back();
      
        if(j!=n-1)
        {
            x ="R";
            rat(m,n,ans,i,j 1);
        }
        x.pop_back();
     
        if(i>0)
        {
            x ="U";
            rat(m,n,ans,i-1,j);
        }
        x.pop_back();
      
        if(j>0)
        {
            x ="L";
            rat(m,n,ans,i,j-1);
        }
        x.pop_back();
        
    */
       
    }
    vector<string> findPath(vector<vector<int>> &m, int n) {
     
     vector<string>ans;
     
     rat(m,n,ans,0,0);
     
     if(ans.size()==0)
     return {"-1"};
     return ans;
    }
};

CodePudding user response:

Seem very likely to me that this code

    if(i>0)
    {
        x ="U";
        rat(m,n,ans,i-1,j);
    }
    x.pop_back();

should be

    if(i>0)
    {
        x ="U";
        rat(m,n,ans,i-1,j);
        x.pop_back();
    }

Same error several times.

The way you have written it, you will remove characters from x that were never put there in the first place.

  • Related