dimanche 30 octobre 2016

C++: Compiler-specific segmentation fault when storing data from file into array

I am writing a C++ program that takes in number from a file ("input10") of this format:

1    0    12
2    3    24
3    8    9
4    9    2
5    10   3
6    11   4
7    14   8
8    16   10
9    16   3
10   17   12

Each number goes into an array p_data[3] (three numbers to each line).

When running in Visual Studio, there is no error and the correct data is stored in the array. I include the #define _CRT_SECURE_NO_WARNINGS here so that I can use strncpy. I am not sure if strncpy is the source of the issue.

When running with g++ -std=c++11 on a CentOS terminal, I get the following error message:

Segmentation fault (core dumped)

I am finding this issue really difficult to debug. Any thoughts?

#include <iostream>
#include <cstring>
#include <string>
#include <stdlib.h>
#include <fstream>
using namespace std;

void get_processes() {
    string curr_line;
    ifstream infile("input10");
    int p_data[3];
    int p = 0;
    char line[1024];

    while (getline(infile, curr_line)) {
        strncpy(line, curr_line.c_str(), sizeof(line));
        line[sizeof(curr_line) - 1] = 0;

        int p_data_count = 0;
        for (int i = 0; line[i] != '\0'; ++i) {
            if (line[i] != ' ') {
                string num = "";
                while (line[i] != ' ') {
                    num += line[i];
                    ++i;
                }

                if (p_data_count < 3) {
                    p_data[p_data_count] = stoi(num);
                    ++p_data_count;
                }
            }
        }
    }

    infile.close();
}

int main() {
    get_processes();

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire