我的链接列表和 valgrind 输出有问题。
不用再说了,这是我的链接列表:
typedef struct Map map;
struct Map
{
void *address;
double free_time;
map* next;
}*map_list;
该列表是使用虚拟头节点创建的。正如您所看到的,该结构体包含一个地址和一个空闲时间,我尝试将它们关联起来。
In the 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 now\n");
printf("the time to check for free is %lf and the maps free time is %lf\n", mtime,current->free_time);
printf("The map contains an address that is time to free\n");
//free_allocated_address(¤t->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 now\n");
}
current = current->next; //FIRST ERROR
}
printf("THE MAP SIZE AFTER REMOVALS IS %d\n", 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->next
and current->next
在我释放了它们之后,但我还是无法摆脱它。
你能建议我一种方法来消除这个错误吗?