大小 8 的无效读取 - Valgrind + C
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];符号!= 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);
}
}
我试图理解此错误的原因。
任何帮助都会很棒!
Valgrind reports error Invalid read of size 8
in the following code.
I have an array declared like,
struct symbol *st[PARSER_HASH_SIZE];
When my program is initialized, all the elements in this array are initailzied as 0.
memset(&st[0], 0, sizeof(st));
My program creates instances of struct symbol
and inserts into the above array depending on the hash value. So few of the elements in this array will be NULL and others will be valid value.
The following code tries to delete the allocated items and valgrind complains at the line,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);
}
}
I am trying to understand the reason for this error.
Any help would be great!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是您正在释放
sym
,然后尝试从(现已释放的)数据中访问值:sym->next
。您可能想要这样的内循环:
The problem is that you're freeing the
sym
, then trying to access a value from the (now-freed) data:sym->next
.You probably want something like this for the inner loop:
还不清楚数组是否包含结构体或指向结构体的指针,
表示它是指向结构体的指针数组。但是你说
“当我的程序初始化时,这个数组中的所有元素都被初始化为0”。
这将条目视为
清除数组的结构
also its not clear if you array is meant to contain structs or pointers to structs
says its an array of pointers to structs. But then you say
"When my program is initialized, all the elements in this array are initailzied as 0."
This is treating the entries like structs
to clear the array do