如何使用 valgrind 在 C 中修复此错误:大小为 8 的写入无效

How can I fix this error in C using valgrind: invalid write of size 8

提问人:LesGEEKs456 提问时间:2/8/2023 最后编辑:Mark RotteveelLesGEEKs456 更新时间:2/15/2023 访问量:98

问:

编译代码后,我遇到了一些关于内存的问题。在我的 Linux 终端上执行 ./valgrind 后,我收到此函数的以下错误:

read_lines_from_file 时大小为 8 的写入无效。

这是我的功能:read_lines_from_file

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>

int lines_count = 0;
char** read_lines_from_file(FILE* file) {
    fseek(file, 0, SEEK_SET);
    char** lines = NULL;// ça renvoie NULL si le fichier est vide
    char  line[100];
    while (fgets(line, 100, file)) {// nous faisons l'hypothèse qu'une ligne ne dépasse pas 100 caractères
        line[strlen(line)-1]='\0';// on enlève le \n
        lines = realloc(lines, (lines_count + 1) * sizeof(char*));
        lines[lines_count] = malloc(strlen(line) + 1);
        strcpy(lines[lines_count], line);
        lines_count++;
    }
    return lines;
}

我不明白它来自哪里以及如何纠正它以消除此错误。

C 存储器 Malloc Valgrind

评论

0赞 Andreas Wenzel 2/8/2023
请注意,同时,已为您删除了不正确的标签(请参阅修订历史记录)。
0赞 pmacfarlane 2/8/2023
什么?lines_count
1赞 Andreas Wenzel 2/8/2023
寻求调试帮助的问题通常应提供问题的最小可重现示例,其中包括函数和所有指令。这允许其他人通过简单地使用复制和粘贴轻松测试您的程序。main#include
0赞 LesGEEKs456 2/8/2023
@pmacfarlane lines_count 是一个全局变量,用于计算行数,代码开头的值为 0。
1赞 datenwolf 2/8/2023
你可以用 , 代替 +,memcpystrcpystrdup

答:

2赞 chux - Reinstate Monica 2/8/2023 #1

代码至少存在以下问题:

不清楚是否有任何解决方案“拆分时大小为 1 的无效写入”。

呼叫者缺少有关读取了多少行的信息

read_lines_from_file,在第二次呼叫时不会重置为 0,因此会向呼叫者传达错误的线路数。

黑客漏洞利用

line[strlen(line)-1]='\0';是 UB,其中读取的第一个字符是 null 字符

此外,输入肯定不包括 .'\n'

 // Better as
line[strcspn(line, "\n")] = '\0';

缺乏错误检查

代码不检查分配错误。

100+ 个字符的行处理不好