2

i was solving the problem https://www.spoj.pl/problems/ACPC11A/

and here is my code :

#include<iostream>
#include<cstdio>
#include<string>
#include<vector>

using namespace std;

int main()
{
int tc,i,n;
scanf("%d",&tc);
while(tc--)
{
    vector<string> v1,v2;
    string str,w;
    scanf("%d",&n);
    int flag=0;
    for(i=0;i<n;i++)
    {
        cin>>str;
        if(str[0]!='#')
        {
            flag=1;
            w=str;
        }
        else if(flag==0)
        {
            v1.push_back(str);
        }
        else
            v2.push_back(str);
    }
    //print v2-->w-->v1
    for(i=0;i<v2.size();i++)
    {
        cout<<v2[i]<<" ";
    }
    if(w!="")
    cout<<w<<" ";
    for(i=0;i<v1.size()-1;i++)
        cout<<v1[i]<<" ";
    cout<<v1[v1.size()-1]<<endl;
    v1.clear();v2.clear();str.clear();w.clear();
}
return 0;
}

i am getting the correct output for the sample test case...but on submission my code gives segmentation fault.

my logic is simple.. i took 2 vectors 1 for storing words before a English word arrives(v1) and other for storing worlds after a English word arrives(v2) after that i print the contents of v2 followed by word and then content of v1.

please help me in understanding why is this code giving segmentation fault.

Amol Sharma
  • 1,521
  • 7
  • 20
  • 40

1 Answers1

4

don't bother guys...i got my mistake

Error is in line for(i=0;i<v1.size()-1;i++)

when v1.size() is 0 ,then as size() returns unsigned value...hence 0-1 will be very large value and hence the SIGSEGV

Amol Sharma
  • 1,521
  • 7
  • 20
  • 40