Hi, I’m super new to C++ and I was working on the Milk Measurement problem, when I encountered the error:
run: line 1: 3 Segmentation fault (core dumped) LD_LIBRARY_PATH=/usr/local/gcc-9.2.0/lib64 ./a.out
My code is below:
#include<string>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include<vector>
#include <cmath>
#include <array>
#include<map>
#include<set>
using namespace std;
map<pair<int,int>,int> visited;
void setIO(string s) {
freopen((s+".in").c_str(),"r",stdin);
freopen((s+".out").c_str(),"w",stdout);
}
vector<int> find_max(int arr[]) {
int max = std::numeric_limits<int>::min();
vector<int> indicies;
for(int p = 0; p < 3;p++) {
if(arr[p]==max) {
indicies.push_back(p);
}
else if(arr[p] > max) {
max = arr[p];
indicies.clear();
indicies = {arr[p]};
}
}
return indicies;
}
int main() {
// setIO("measurement");
string names[3] = {"Bessie", "Elsie", "Mildred"};
int production[3] = {7,7,7};
set<string> previous_winners; set<string> cur_winners;
// cout << (previous_winners == cur_winners);
int l; cin >> l;
map<int, string> day_to_name; map<int, int> day_to_change;
int days[l];
int counter = 0;
for(int i = 0; i < l;i++) {
int day;string name, change;cin >> day >> name >> change;
days[i] = day;
day_to_name[day] = name;
cout << day << endl;
if(change[0] == '+') {
day_to_change[day] = change[1];
}
else {
day_to_change[day] = -1*(change[1]);
}
}
sort(days, days + l);
for(int i: days) {
string cur_name = day_to_name[i];
if(cur_name == "Bessie") {
production[0] += day_to_change[i];
}
else if(cur_name == "Elsie") {
production[1] += day_to_change[i];
}
else {
production[2] += day_to_change[i];
}
vector<int> maxima = find_max(production);
for(int j: maxima) {
cur_winners.insert(names[j]);
}
if(cur_winners != previous_winners) {
counter++;
}
previous_winners = cur_winners;
cur_winners.clear();
}
cout << counter;
return 0;
}
The test case I am using is the sample test cast:
4 7 Mildred +3 4 Elsie -1 9 Mildred -1 1 Bessie +2
In my limited experience, this is probably due to some part of my code where I end up calling an index that doesn’t exist or something of the sort. From some debugging cout statements, my code stopped printing somewhere within the first for loop in main(), so the problem is(probably?) there. Where could my code be outputting this segmentation fault error?