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

标签 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 实际上我忽略了有两条不同的线,因为我想在最后删除第一条,因为那里没有保存数据。但是你能帮我找到这个错误的解决方案吗?

最佳答案

你的问题是这一行

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

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

该语句的另一个问题是,无论您需要多少内存,您都将总是分配100 字节。您提供给 realloc 的尺寸参数是新的尺寸。

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

关于C - 通过读取 csv 文件获取调试断言失败错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28106180/

相关文章:

python - 错误 : ambiguous overload for 'operator/'

c - 使用 makefile 编译时出现链接器错误

java - 如何在 Gradle 运行任务中启用断言

java - 如何启用断言?

c - 单链表无法正确添加到开头

c - Valgrind 'noise' 是什么意思?

c# - 如何在阅读行时不断检查用户是否按 esc?

python-3.x - readline() 一次返回一个字符

node.js - 使用 Node.JS Readline : "TypeError: rl is not async iterable"

c# - .NET assert 断言已启用