0

I am writing a code which will edit a string.But, my code is giving a segmentation fault for an input "zzzzzzzzzz". I am unable to figure out the reason behind the segmentation fault.

#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
 {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;cin>>t;
while(t--)
{
    string s;cin>>s;
    int l=s.size();
    int i=1;
    cout<<l;
    //s.erase(s.begin()+5);
    while(i<(l-1))
    {
        cout<<i<<" ";
        s.erase(s.begin()+i);
        i=i+2;
    }
    cout<<s<<endl;
}
//code
return 0;
  • Clearly it's that you are calling `s.erase(s.begin()+i);` when `i` is greater than or equal to the size of `s`. Suggest you use a debugger to understand exactly why this is happening. – john Jun 18 '20 at 08:06
  • Not the answer, but: [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice), [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h). – HolyBlackCat Jun 18 '20 at 08:06
  • But i can not go more then 'l-1', and the length of string is 'l'.So, we are surely not making 'i' greater than size of 's' – anita shrivastava Jun 18 '20 at 08:10
  • No because `l` is the size of the original string not the size of the current string. – john Jun 18 '20 at 08:18

2 Answers2

1

It seems that you are hoping that this code

while(i<(l-1))

will stop you trying to erase character in s that don't exist. But remember that l is the size of the original string, and in the loop you progressively shorten the string. I guess what you really need is

while(i+1<s.size())

That way you are always testing against the latest size of s.

Note that while(i<s.size()-1) is not so good because s.size() is an unsigned integer. If the string has zero size, then s.size()-1 will cause unsigned overflow and the loop will not terminate.

john
  • 85,011
  • 4
  • 57
  • 81
0

you are getting segmentation fault because you each time your string size will be decreased and you are try to access the out of range part (s.erase(s.begin()+i);) in this statement to correct this just add one if statement before it like

if(s.begin()+i !=s.end())
s.erase(s.begin()+i);

this will ensure that you are not going out of bound