Search code examples
c++vectorruntime-errorc++17

Getting SIGABRT while using vector


int maxOccured(int L[], int R[], int n, int maxx){
    
        // int v[maxx]={0};
        vector<int> v(maxx);
        for(int i=0; i<n; i++){
            v[L[i]]+=1;
            v[R[i]+1]-=1;
        }
        int max=v[0];
        int res=0;
        for(int i=1; i<maxx; i++){
            v[i]+=v[i-1];
            if(v[i]>max){
                max=v[i];
                res=i;
            }
        }
        return res;
        
    }

here in my code if I am using an array of same size it is working fine but while using a vector I am getting an error of

Abort signal from abort(3) (SIGABRT)

Solution

  • Here are few things you should be absolutely sure of:

    1. n <= max (to avoid out of bounds runtime error)
    2. 0 <= L[i] < n and 0 <= R[i]+1 < n for all values of i from 0 to n-1(provided condition 1 is satisfied). (Again to avoid out of bounds runtime error)
    3. maxx is not too large (of the order of 10^5 or 10^6) otherwise your vector won't get enough storage to store its elements and your program will crash.