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.
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.
-g
flag.gdb a.out
(or name of program)(gdb) run
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.