链表valgrind读取大小无效



我有一个问题与我的链表和valgrind输出。话不多说,下面是我的链接列表:

typedef struct Map map;
struct Map
{
    void *address;
    double free_time;
    map* next;
}*map_list;

列表是使用虚拟头节点创建的。如你所见,这个结构体保存着一个地址和一个空闲时间,我试着把它们联系起来。

find_and_free函数中,我使用一个时间搜索这个列表,如果这个时间小于列表中存储的时间,我就释放保存的地址。然后我也释放列表节点

这个函数用于查找任何小于我传递的空闲时间。如果它更小,我释放存储到列表中的地址,然后调用delete_map_node函数来释放列表的节点。

void find_and_free_address(map *root, double mtime)
{
    map *current = root->next;
    assert(current);
    while(current)
    {
        if(current->free_time < mtime)
        {
            printf("there is something to FREE nown");
            printf("the time to check for free is %lf and the maps free time is %lfn", mtime,current->free_time);
            printf("The map contains an address that is time to freen");
            //free_allocated_address(&current->address);
            free(current->address);
            delete_map_node(map_list, current->free_time);
            //delete(map_list,current->free_time);
            //return next;
        }
        else
        {
            printf("there is nothing to free nown");
        }
        current = current->next; //FIRST ERROR
    }
    printf("THE MAP SIZE AFTER REMOVALS IS %dn", map_size(map_list));
}

这是delete_map_node函数

map* delete_map_node(map *root,double ftime)
{
    if (root==NULL)
    {
        return NULL;
    }
    //map *temporary;
    if (root->free_time == ftime)
    {
        map *temporary = root->next;
        free(root); //SECOND ERROR
        root = temporary;
        return temporary;
    }
    root->next = delete_map_node(root->next, ftime);
    //free(root->address);
    return root;
}

我知道这两者只能组合成一个功能。

valgrind报告没有内存泄漏或未初始化的值。但是,当我执行以下命令时:

valgrind --tool=memcheck --leak-check=full --track-origins=yes -v ./a.out

得到以下输出:

==6807== Invalid read of size 4
==6807==    at 0x8049228: find_and_free_address (Map.c:123)
==6807==    by 0x8048DA6: second_iteration (List.c:150)
==6807==    by 0x8048C6B: first_iteration (List.c:113)
==6807==    by 0x8048908: main (Fscanf.c:63)
==6807==  Address 0x42005bc is 12 bytes inside a block of size 16 free'd
==6807==    at 0x402AF3D: free (vg_replace_malloc.c:468)
==6807==    by 0x804929F: delete_map_node (Map.c:142)
==6807==    by 0x80492C1: delete_map_node (Map.c:147)
==6807==    by 0x8049216: find_and_free_address (Map.c:113)
==6807==    by 0x8048DA6: second_iteration (List.c:150)
==6807==    by 0x8048C6B: first_iteration (List.c:113)
==6807==    by 0x8048908: main (Fscanf.c:63)

我可以看到,错误是我访问root->nextcurrent->next后,我已经释放他们,但我没有设法做到没有它。

你能建议我一个方法来消除这个错误吗?

我看到的一个问题是,在delete_map_node中,您释放root(可能是map_listfind_and_free_address传递),但您实际上没有更改map_list,这意味着当delete_map_node返回map_list变量指向未分配的内存时。之后访问map_list会导致未定义行为

简单的解决方案是将delete_map_node的返回值赋给map_list:

map_list = delete_map_node(map_list, current->free_time);

另外,当delete_map_nodefind_and_free_address函数中释放列表中的current节点时会发生什么?那么current = current->next也会导致未定义行为

相关内容

  • 没有找到相关文章

最新更新