Domanda

I tried to solve the needle in the haystack problem in ideone, but I'm getting a SIGSEGV.

This is my code:

    //start
    #include<cstring>
    #include<cstdio>
    #include<vector> 
    using namespace std;


    int *overlap;
    char *pattern;
   //used Knuth morris prat algo
   void calcoverlap()
   {
    overlap[0] = 0;
    unsigned int length,i,len;  
    length=strlen(pattern);

    while(i<length)
    {
        if (pattern[i] == pattern[len])
        {
            len++;
            overlap[i] = len;
            i++;
        }
        else
        {
            if (len != 0)
            {
                len = overlap[len-1];
            }
            else
            {
                overlap[i++] = 0;
            }
        }

    }
   }
    //this is final function for pattern matching
    vector< int > patternmatching(int m)
{
vector< int > V;
int i = 0, j = 0;
char ch;
while(1)
{
ch = getchar();
if(ch == '\n') break;
while(1)
{
if(ch == pattern[j])
{
j++;
if(j == m)
{
V.push_back(i-m+1);
j = overlap[j];
}
break;
}
else if(j == 0) break;
else j = overlap[j];
}
i++;
}
    return V;
    }




   int main()
   {
        int n,i,sz;
        vector<int> V;
        while(scanf("%d",&n)==1)
        {   
            gets(pattern);
            calcoverlap();
            V=patternmatching(n);
            sz = V.size();
           for(i=0; i < sz; i++)
            printf("%d\n",V[i]);
            if(!sz) printf("\n");
            delete[] pattern;
            delete[] overlap;
        }
         return 0;
        }    

Can someone please explain why I am getting this error only while uploading the input when normally this program runs fine and dandy.

È stato utile?

Soluzione

It's very easy to isolate a segfault (includes sigsegv) using a debugger.

If you are developing on Unix, please run your code in a debugger.

  1. Compile your code with the -g flag.
  2. Run your code in gdb as follows - gdb a.out (or name of program)
  3. Run: (gdb) run
  4. Your program will crash at your segfault. It should show you the exact line number it happens on. You may have to type bt or where to trace it back.

In IDEs it's even easier. Usually you debug by looking for a debug symbol, often graphically represented by a bug (e.g. Eclipse). I'm not familiar with the IDE you use so perhaps if you have trouble someone could post an answer specific to that IDE.

Altri suggerimenti

As Dav suggested in the comment, you use an uninitialized pointer (pattern) with gets, thus the segfault.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top