分段错误,while 循环中的 fgets

Segmentation fault, fgets in while loop

我尝试多次读入一个文件而不是一次。 在尝试时,我遇到了很多分段错误。带有 while 循环的程序部分如下所示:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

/* General use buffer */
#define STRLEN 8196
char    string[STRLEN];


int lines = 1024;
char    **line;
int linemax;

int longest=0;


int main(){
int len,i;
int zwei = 1;
FILE * fp;
char    *s;
int debug =  0;
line=(char **)malloc(sizeof(char *) * 1024);
do{
    if ( (fp = fopen("rhel7_160731_0606.nmon", "r")) == NULL) {
        perror("failed to open file");      

                perror("fopen");
        exit(75);
    }
printf("where is the problem1,3\n");
    for (i = 0; fgets(string, STRLEN, fp) != NULL; i++) {
        if (i >= lines) {
            lines += 1024;
            line = (char **)realloc((void *)line, sizeof(char *) * lines);
        }

        if (string[strlen(string)-1] == '\n')
            string[strlen(string)-1] = 0;
        if (string[strlen(string)-1] == '\r')
            string[strlen(string)-1] = 0;
        if (string[strlen(string)-1] == ' ')
            string[strlen(string)-1] = 0;
        if (string[strlen(string)-1] == ',')
            string[strlen(string)-1] = 0;
        len = strlen(string) + 1;

        if (len > longest)
            longest = len;
        s = malloc(len);
        strcpy(s, string);
        line[i] = (char *)s;
    }
    linemax = i;
    lines = i;

    if (debug)
        for (i = 0; i < linemax; i++)
            printf("line %d lastline %s\n", i, line[i-1]);

zwei++;

}while(zwei<4);

return 0;
}

它没有挂起或以分段错误结束。

您似乎忘记了为 line 分配内存。此处失败:line[i] = (char *)s。我认为您需要将 lines 设置为零,因为只有当您的迭代器 ilines.

增长时才重新分配 line 此外,修复此问题:while(zwei > 4)while(zwei < 4)。而且,您 需要 free 您分配的内存 - 因为您将所有指针存储在 line 中,它不会很复杂 - 只是一个循环。