This question already has an answer here:
Closed 5 years ago.
C Linked List valgrind Invalid Read of Size
(1个答案)
我的理解是,每一个Maloc我们在离开之前都应该自由。根据valgrind的报告,我没有泄密。也就是说,valgrind报告这个代码有一个错误:
为了简洁起见,下面只是链接列表代码的一部分片段,它显示了节点类型和我malloc或释放节点的代码部分。
实际上,看看你的代码,它几乎和上面的例子一样明目张胆(正如BLUEPIXY在他的comment中指出的那样):
修复:
(1个答案)
我的理解是,每一个Maloc我们在离开之前都应该自由。根据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;
}
}
}
最佳答案
错误是告诉您在释放内存后正在使用指向已释放内存的指针:
void *m = malloc(8);
char *s = m + 4;
free(m);
*s = 29; // This would generate that warning.
int c = *s; // This would also generate that warning.
实际上,看看你的代码,它几乎和上面的例子一样明目张胆(正如BLUEPIXY在他的comment中指出的那样):
free(curr_node);
curr_node = curr_node->next;
修复:
node *next = curr_node->next;
free(curr_node);
curr_node = next;
关于c - Valgrind错误,但无泄漏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24275939/
10-15 14:57