c - 段错误,while 循环中的 fgets

标签 c linux while-loop fopen fgets

我尝试多次读入一个文件而不是一次。 在尝试时,我遇到了很多段错误。带有 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为零,因为您重新分配了 line只有当你的迭代器 i种植者比lines .

另外,解决这个问题:while(zwei > 4)while(zwei < 4) .而且,您需要free您分配的内存 - 因为您将所有指针存储在 line 中,它不会很复杂 - 只需一个循环。

关于c - 段错误,while 循环中的 fgets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39537203/

相关文章:

c - 函数指针转换

c++ - 如何让 GCC 报告每次出现未声明的符号?

c - 是否可以实现不执行任何系统调用的 C 程序?

sql - while 循环遇到符号 > 错误

java - Hangman while 循环不适用于 ||

将 `while` 循环转换为 `for` 循环

c - 字符串和无限循环中的堆栈粉碎

linux 2.6调度与抢占——preempt_count的使用

php - 从 CLI 和 PHPMyAdmin 中删除 PHP 错误

java - 从正在运行的程序中获取变量