简体   繁体   中英

Return segmentation fault, after all code has been executed

The following code is my solution to the cp problem in this link: http://www.usaco.org/index.php?page=viewproblem2&cpid=761

#include<bits/stdc++.h>
using namespace std;

int main(){
    freopen("measurement.in","r",stdin);
    freopen("measurement.out","w",stdout);  

    vector<tuple<int,int,int>> records;
    
    int n; scanf("%d", &n);
    
    int day; char* cow; char sign; int change;
    for (int i=0;i<n;i++){
        scanf("%d %s %c%d", &day, cow, &sign, &change);
        
        if (sign == '-') change = -change;
        int id;
            
        if (strcmp(cow,"Bessie") == 0) id = 0;
        if (strcmp(cow,"Elsie") == 0) id = 1;
        if (strcmp(cow,"Mildred") == 0) id = 2;
    
        records.push_back(make_tuple(day,id,change)); 
    }

    sort(records.begin(),records.end());
    
    int galls[3] = {7,7,7};

    vector<int> board {0,1,2};  
    
    int num = 0;
    for (auto record : records){
        vector<int> temp = board;
        galls[get<1>(record)]+=get<2>(record);
        
        int max_o = 0;
        for(int i=0;i<3;i++)
            max_o = max(max_o,galls[i]);
    
        board.clear();
        for (int i=0;i<3;i++)
            if (galls[i] == max_o) board.push_back(i);  

        if (board.size() != temp.size()){
            num++;
        } else{
            for (int i=0;i<board.size();i++){
                if (board[i] != temp[i]){
                    num++;
                    break;
                }
            }
        }
    }

    cout << num;
}

This solution returns the correct value and all code is executed, but after all code is run, Segmentation fault (core dumped) is returned. I have never encountered a segmentation fault after all code has been executed so I a very confused as to why this is happening. Can someone help here?

This input file measurement.in is as follows:

4
7 Mildred +3
4 Elsie -1
9 Mildred -1
1 Bessie +2

Turns out the problem was with using the c-strings strcmp function. I used the string compare function instead and it worked!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM