Home > front end >  Segmentation fault caused by repeating pop_back() and push_back()
Segmentation fault caused by repeating pop_back() and push_back()

Time:11-26

When I run the following code in Clion(an IDE) with c 11. I ran into a segmentation fault. But if I delete the if statement, add else before pop_back, remove push_back, or remove pop_back(do them separately). There would be no error. So why there would be a segmentation fault and why doing any of the above would eliminate the error?

#include "vector"
using namespace std;

int main() {
    vector<int> test;
    for(int i = 0; i < 10000; i  ){
        if(i % 2 == 0)
            test.push_back(i);
        test.pop_back();
    }
}

Edit: Some people say it's because pop_back from empty vector, but if I remove push_back() there won't be any problem(even if I push_back some elements before the loop).

CodePudding user response:

You are popping from the vector when it is empty. Using pop_back() from an empty vector results in undefined behaviour which means:

  • your program could crash
  • your program could print some nonesens
  • your program could continue normally
  • your program could continue normally, but have some other strange seemingly unrelated behaviour later
  • or some other behaviour

Consider this code:

#include <vector>
#include <iostream>

using namespace std;

int main() {
  vector<int> test;
    
  for (int i = 0; i < 10; i  ) {
    if (i % 2 == 0)
      test.push_back(i);

    if (test.empty())
      cout << "stack is empty" << endl;
    else
      test.pop_back();
  }
}
  • Related