【发布时间】:2023-03-13 09:17:01
【问题描述】:
这是我的代码 sn-p,我在尝试释放分配的内存时遇到错误。
int main()
{
int value = 10;
totValues = pow(2, value);
head = (node_t *)calloc(totValues, sizeof(node_t));
createNode(head, 10, 20);
free(head);
}
void createList(node_t *head, int tag, int index)
{
node_t temp = (node_t) calloc(1, sizeof(sizeof(node_t)));
temp->tag = tag;
temp->next = head[index];
head[index] = temp;
free(temp);
}
我正在尝试释放 head 和 temp 节点,但这不起作用并且我看到错误。我正在使用 valgrind 跟踪内存泄漏。不知道我做错了什么。
【问题讨论】:
-
一方面,虽然你没有显示
totValues我怀疑calloc(sizeof(totValues), sizeof(node_t));应该是calloc(totValues, sizeof(node_t)); -
你为什么要
sizeof(sizeof(node_t))?将sizeof运算符加倍不是您想要的。 -
我更正了,但堆仍然被占用
-
你不应该释放
temp,因为你把它和head[index] = temp;放在了列表中。 -
为什么要分配内存,用有用的信息填充它,然后释放它?!这有什么用?
标签: c struct heap-memory dynamic-memory-allocation