gpt4 book ai didi

c - 大小 8 的无效读取 - Valgrind + C

转载 作者:太空狗 更新时间:2023-10-29 16:25:41 28 4
gpt4 key购买 nike

Valgrind 在以下代码中报告错误 Invalid read of size 8

我有一个数组声明如下,

struct symbol *st[PARSER_HASH_SIZE];

当我的程序初始化时,这个数组中的所有元素都被初始化为0。

memset(&st[0], 0, sizeof(st));

我的程序创建了 struct symbol 的实例,并根据散列值插入到上述数组中。此数组中的元素很少为 NULL,其他元素为有效值。

下面的代码试图删除分配的项目和 valgrind 在该行提示,sym = st[i];符号!=空; sym = sym->下一步

struct symbol *sym = NULL;

/* cleaning the symbol table entries */
for(i = 0; i < PARSER_HASH_SIZE; i++) {
for(sym = st[i]; sym != NULL; sym = sym->next) { /* <-- Valgrind complains here */
free(sym);
}
}

我正在尝试了解此错误的原因。

任何帮助都会很棒!

最佳答案

问题是您正在释放 sym,然后尝试从(现已释放的)数据访问一个值:sym->next

你可能想要这样的内循环:

struct symbol *next_sym = NULL;

for(sym = st[i]; sym != NULL; ) {
next_sym = sym->next;
free(sym);
sym = next_sym;
}

关于c - 大小 8 的无效读取 - Valgrind + C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4035769/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com