Search code examples
c++arraysvectordynamicfault

Segmentation fault in a dynamically allocated vector in C++


I'm writing a code to check for zig-zag arrays(arrays whose 3 consecutive elements are not in increasing or decreasing order) and return the minimum number of elements to be deleted to make it zig-zag. But I'm getting segmentation fault for large arrays.

#include <bits/stdc++.h>

using namespace std;

int minimumDeletions(vector < int > a,int n){
int i,j;
j=n;
for(i=0;i<n;i++){
    if(a[i]>a[i+1]){
        if(a[i+1]>a[i+2]){
            a.erase(a.begin()+(i+2));
            i--;
            n--;
            continue;
        }
        else{continue;}
    }
    if(a[i]<a[i+1]){
        if(a[i+1]<a[i+2]){
            a.erase(a.begin()+(i+2));
            i--;
            n--;
        }
        else{continue;}
    }
}
j=j-n;
return j;
}

int main() {
int n;
cin >> n;
vector<int> a(n);
for(int a_i = 0; a_i < n; a_i++){
   cin >> a[a_i];
}
// Return the minimum number of elements to delete to make the array zigzag
int result = minimumDeletions(a,n);
cout << result << endl;
return 0;
}

Solution

  • a[i+1]
    

    Here you are reaching an element not stored in the vector. When i=n-1, you for a[n] which is not stored in your vector basically.