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 != NULL; sym = sym->next
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;
}
也不清楚数组是包含结构还是指向结构的指针
struct symbol *st[PARSER_HASH_SIZE];
表示它是一个指向结构的指针数组。但后来你说
“当我的程序初始化时,这个数组中的所有元素都被初始化为0。”
memset(&st[0], 0, sizeof(st));
这将条目视为结构
要清除数组,请执行以下操作
for (int i = 0; i < PARSER_HASH_SIZE; i++)
{
st[i] = 0;
}
_dummy=_userTable[i]; (好的) 删除_userTable[i];