【发布时间】:2014-06-18 01:53:56
【问题描述】:
我的理解是,对于每个 malloc,我们应该在退出之前释放。根据 valgrind 报告,我没有泄漏。也就是说,valgrind 报告此代码有错误:Address 0x402613c is 4 bytes inside a block of size 8 free'd
为简洁起见,下面只是部分链表代码的片段,显示了节点类型和我 malloc 或释放节点的代码部分。
typedef struct node
{
int n;
struct node* next;
}
node;
// global variable for the head of the list
node* head = NULL;
int main(void)
{
// user menu
while (true)
{
printf("Please choose an option (0, 1, 2): ");
int option = GetInt();
switch (option)
{
// quit
case 0:
free_nodes(head);
printf("Goodbye!\n");
return 0;
// snipped: code that calls insert and print functions
bool insert_node(int value)
{
// create new node
node* new_node = malloc(sizeof(node));
if (new_node == NULL)
{
return false;
}
// snipped: some code that adds nodes to linked list
}
/**
* Frees all of the nodes in a list upon exiting the program.
*/
void free_nodes(node* list)
{
// initialize pointer
node* curr_node = head;
// initialize variable for end of list
bool is_end = false;
// free nodes
while (!is_end)
{
// if an empty list, free node and exit
if (curr_node->next == NULL)
{
free(curr_node);
is_end = true;
}
// else free node list until end of list if found
else
{
free(curr_node);
curr_node = curr_node->next;
}
}
}
【问题讨论】:
-
free(curr_node); curr_node = curr_node->next;: 你不应该使用已经发布的指针。