C - 通过读取csv文件获取调试断言失败错误

时间:2015-01-23 08:56:15

标签: c readline assertion fgetc

我只是在C中执行一个程序,它必须以csv格式读取不同的文件。每个文件由两行组成。 第一行描述了保存的主题,而第二行包含主题的数据。每个文件都有 6列。数据是日期,来源和类别等信息。我实际上写了一个程序来获取路径和 将内容放在一个动态字符串数组中,但始终存在一个调试断言错误,它会一直崩溃。我的代码是:

char* readfile(char csvpath[]) {
FILE *csv;
int c;
int countcontent = 100;                 //counter for the length of the content array
int counter = 0;                    //counter  of the amount of the inserted chars
char *temp;                     //temp = buffer
char *content = (char*)calloc(100,sizeof(char));    //content of the file
csv = fopen(csvpath,"r");
while(c = fgetc(csv) != EOF) {              //while file isnt at the end
    if(countcontent <= counter) {
        realloc(content,100*sizeof(char));
        countcontent += 100;
    }
    temp = (char*)calloc(20,sizeof(char));
    fgets(temp,20,csv);
    content = concat(content,temp);         //concat is my own function and add the 2. string behind the 1.
    counter+= 20;
}
fclose(csv);
return content;}

Assert Screenshot 实际上我忽略了有两个不同的行,因为我想在最后删除第一个,因为没有数据保存在那里。但是,你能帮我找到这个错误的解决方案吗?

1 个答案:

答案 0 :(得分:1)

你的问题就在这一行

realloc(content,100*sizeof(char));

realloc函数返回指向重新分配的内存的指针。想想如果realloc调用只能调整已经分配的块的大小,并且必须实际分配一个全新的内存块,会发生什么,因为它无法自动更新你传递的指针它。

该声明的另一个问题是,您需要多少内存并不重要,总是分配100个字节。您提供给realloc的尺寸参数是 new 尺寸。

哦,请记住realloc可能会失败,并返回NULL指针。如果您不想丢失原始指针,则需要使用临时变量来存储返回的指针,并检查它是否为NULL