1

Basically, I have this function which counts the number of lines in a text file and it is giving me a headache. It works like a charm with small files (say with 50000 lines). However, for some reason, I get a segmentation fault error when I try to count the lines in a file that has 1 million lines. This is the code:

int countlines(char *filename)
{
    // count the number of lines in the file called filename
    FILE *fp = fopen(filename,"r");
    int ch=0;
    int lines=0;

    if (fp == NULL)
        return 0;

    while ((ch = fgetc(fp)) != EOF)
    {
        if (ch == '\n')
            lines++;
    }
    fclose(fp);
    return lines;
}

I have honestly tried a thousand variations of this and I can't figure out what's wrong. It reaches the line count of 1000000 but then it gives me a Segmentation fault error. Any help will be greatly appreciated!

Edit: Since everyone is saying it works for them, I'll show you what I have in my main function.

int main(int argc, const char * argv[])
{
    int X_len = countlines("/homes/myworkspace/X.txt");
    int X[X_len][4];
    printf("\n X_len = %d",X_len);
}
4

2 回答 2

2

这就是问题

int X[X_len][4];

X_len 大于 1000000 时,您没有足够的内存用于(堆栈)数组。

尝试动态分配(堆

int (*X)[4];
X = malloc(X_len * sizeof *X);
if (X == NULL) /* error */;
// ...
free(X);
于 2014-07-15T10:35:52.540 回答
0

我想说问题出在这里:

 int X[X_len][4];

这会在堆栈上分配内存,可能只有 4MB,这可以解释在 1 000 000 行之后失败。

我建议在堆上分配它:

int *X = (int*)malloc(X_len * sizeof(int) * 4);
于 2014-07-15T10:36:44.963 回答