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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4035769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:49:33  来源:igfitidea点击:

Invalid read of size 8 - Valgrind + C

cvalgrind

提问by Navaneeth K N

Valgrind reports error Invalid read of size 8in the following code.

ValgrindInvalid read of size 8在下面的代码中报错。

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.

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

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

My program creates instances of struct symboland 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.

我的程序struct symbol根据哈希值创建和插入上述数组的实例。所以这个数组中的元素很少为 NULL,其他元素将是有效值。

The following code tries to delete the allocated items and valgrind complains at the line, sym = st[i]; sym != NULL; sym = sym->next

以下代码尝试删除分配的项目,而 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);
    }
}

I am trying to understand the reason for this error.

我试图了解此错误的原因。

Any help would be great!

任何帮助都会很棒!

回答by ZoogieZork

The problem is that you're freeing the sym, then trying to access a value from the (now-freed) data: sym->next.

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

You probably want something like this for the inner loop:

对于内部循环,您可能想要这样的东西:

struct symbol *next_sym = NULL;

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

回答by pm100

also its not clear if you array is meant to contain structs or pointers to structs

也不清楚你的数组是否意味着包含结构或指向结构的指针

struct symbol *st[PARSER_HASH_SIZE];

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."

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

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

This is treating the entries like structs

这是将条目视为结构

to clear the array do

清除阵列做

for (int i = 0; i < PARSER_HASH_SIZE; i++)
{
    st[i] = 0;
}