c -意外的分段故障-我做错了什么



我一直在努力提高我的C编程技能,但我总是遇到一个我似乎无法解决的错误。这个程序读入一个由换行符分隔的整数列表。这个位发生在read_integer_file…我没有问题处理这里的输入。当我将数据通过out传递回main时,我遇到了问题。

#include <stdlib.h>
#include <stdio.h>
int read_integer_file(char* filename, int* out)
{
    FILE* file;
    file = fopen(filename, "r");
    /* check if the file open was successful */
    if(file == NULL)
    {
        return 0;
    }
    int num_lines = 0;
    /* first check how many lines there are in the file */
    while(!feof(file))
    {
        fscanf(file, "%in");
        num_lines++;
    }
    /* seek to the beginning of the file*/
    rewind(file);
    out = malloc(sizeof(int)*num_lines);
    if(out == NULL)
        return 0;
    int inp = 0;
    int i = 0;
    while(!feof(file))
    {
        fscanf(file, "%in", &inp);
        out[i] = inp;
        printf("%in", out[i]); /* <---- Prints fine here! */
        i++;
    }
    return num_lines;
}
int main(int argc, char** argv)
{
    if(argc < 2)
    {
        printf("Not enough arguments!");
        return -1;
    }
    /* get the input filename from the command line */
    char* array_filename = argv[1];
    int* numbers = NULL;
    int number_count = read_integer_file(array_filename, numbers);
    for(int i = 0; i < number_count; i++)
    {
        /* Segfault HERE */
        printf("%in", numbers[i]);
    }
}

您没有为数字分配任何内存。目前,它没有指向任何地方。当它返回到调用函数时,它仍然没有指向任何地方。将指针传递给指向函数的指针,以便在函数内部分配该指针。

int read_integer_file(char* filename, int** out)
{
     ...
     *out = malloc(sizeof(int)*num_lines);
     ...
     int number_count = read_integer_file(array_filename, &numbers);

这是你的代码工作的一个版本。还要记住,fscanf只是跳过n,就像你写fscanf(file, "%d");

如果你没有设置一个变量来处理它所读取的内容编译器可能看不到它,但你可能会得到一个错误…

代码如下:

#include <stdlib.h>
#include <stdio.h>
int read_integer_file(char* filename, int **out)
{
    FILE* file;
    file = fopen(filename, "r");
    /* check if the file open was successful */
    if(file == NULL)
    {
        return 0;
    }
    int num_lines = 0;
    int garbi;
    char garbc;
    /* first check how many lines there are in the file */
    while(!feof(file))
    {
        fscanf(file, "%d", &garbi);
        fscanf(file, "%c", &garbc);
        if (garbc=='n') ++num_lines;
    }
    /* seek to the beginning of the file*/
    rewind(file);
    int *nbr = malloc(sizeof(int)*num_lines);
    if(nbr == NULL)
        return 0;
    int i = 0;
    while(!feof(file))
    {
        fscanf(file, "%d", &nbr[i++]);
        fscanf(file, "%c", &garbc);
    }
    *out=nbr;
    return num_lines;
}
int main(int argc, char** argv)
{
    if(argc < 2)
    {
        printf("Not enough arguments!");
        return -1;
    }
    /* get the input filename from the command line */
    char* array_filename = argv[1];
    int *numbers = NULL;
    int number_count = read_integer_file(array_filename, &numbers);
    int i;
    for(i = 0; i < number_count; ++i)
        printf("%dn", numbers[i]);
    return 0;
}

最新更新