jeudi 25 février 2021

Segmentation Fault Error when assigning values to array

I'm currently doing a basic simulation problem in USACO. I'm pretty sure I've done the algorithm for this problem correctly, however, when I try to assign values to array, I get the error: run: line 1: 3 Segmentation fault (core dumped) LD_LIBRARY_PATH=/usr/local/gcc-9.2.0/lib64 ./a.out. This is my code:

#include <iostream>
#include<string>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include<vector>
#include <cmath>
#include <array>
using namespace std;
void setIO(string s) { // the argument is the filename without the extension
    freopen((s+".in").c_str(),"r",stdin);
    freopen((s+".out").c_str(),"w",stdout);
}
int main() {
    // setIO("speeding");
    string new_signal = "";
    int m, n; cin >> m >> n;
    int arr1[n+m] = {0};
    int arr2[n+m] = {0};
    for(int i = 0; i < n+m; i++) {
        int a, b; cin >> a >> b;
        arr1[i] = a;
        arr2[i] = b;
        // cout << n+m;
    }
    
    int road_limits[100] = {0};
    int counter = 0;
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < arr1[i]; j++) {
            road_limits[counter] = arr2[i];
            counter++;
        }
    }
    counter = 0;
    int max_over_limit = -200;
    for(int i = n; n < n+m; n++) {
        for(int j = 0; j < arr1[i]; j++) {
            if((arr2[i] - road_limits[counter]) > max_over_limit){
                max_over_limit = (arr2[i] - road_limits[counter]);
            }
            counter++;
        }
    }
    
    cout << max_over_limit;
    return 0;
}

After debugging with print statements, it appears that my code gets the Segmentation Fault error somewhere in the first for loop where I assign the values of arr1 and arr2(no cout statements run past that point). I'm not why this would be the case though. I'm relatively new to using C++, so is there something that I'm misunderstanding that causes this error?

Aucun commentaire:

Enregistrer un commentaire