Home > Net >  C - segmentation fault when using vectors
C - segmentation fault when using vectors

Time:10-14

i was working on a problem from LeetCode about finding intersection elements in two different arrays.

and when i pass the input it throws a segmentation fault.

here is my solution (the solve() function only):

vector<int> solve(){
    int n,m;
    cin >> n >> m;
    vector<int> arr1, arr2;
    for (int i = 0; i < n; i  ){
        cin >> arr1[i];
    }
    for (int i = 0; i < m; i  ){
        cin >> arr2[i];
    }
    sort(arr1.begin(), arr1.end());
    sort(arr2.begin(), arr2.end());

    vector<int> result;
    int i = 0, j = 0;
    while (i < n && j < m){
        if (arr1[i] == arr2[j]){
            result.push_back(arr1[i]);
            i  ;
            j  ;
        }
        else if(arr1[i] > arr2[j]){
            j  ;
        }
        else {
            i  ;
        }
    }
    return result;
}

CodePudding user response:

This happens because your vectors, arr1 and arr2 start off with a length of 0 each. When you try to set a certain index of them, this assumes that the index is already allocated, meaning the vector is long enough to contain that index, which it doesn't in your code.

To solve this, the best solution would be to simply call push_back instead of indexing the vector. This works because push_back will allocate more memory if needed.

for (int i = 0; i < m; i  ) {
    int x;
    cin >> x;
    arr1.push_back(x);
}

CodePudding user response:

As the comments mentioned, your vectors, as constructed have zero elements. So accessing any element like arr1[i] is an error.

You can either construct your vectors with a specific size or you can use push_back to insert an element at the end.

  • Related