【发布时间】:2015-05-19 18:21:57
【问题描述】:
我正在学习链表,它们给我带来了很多麻烦。 我用这个调用来调用函数:
pop(&list);
这是代码:
void pop(NODE** first) {
if(*first != NULL && first!= NULL){
NODE* ptr = *first;
while(ptr->next->next != NULL){
ptr = ptr->next;
}
free(ptr->next);
ptr->next = NULL;
}
即使我一次调用它也会导致内存泄漏错误..
多次调用该函数时,内存泄漏错误较多。
提前致谢,Mimpopo。
编辑:节点的定义
typedef struct node {
int data;
struct node *next;
} NODE;
完整代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} NODE;
NODE* insert(NODE *first, int n){
// create new node
NODE* new = (NODE*)malloc(sizeof(NODE));
new->data = n;
new->next = NULL;
// if first is NULL, this will be the first
if(first == NULL)
return new;
// otherwise, place it correctly
NODE* ptr = first;
// check inserting at the begining
if(ptr->data > new->data){
new->next = ptr;
return new;
}
// insert in the middle
while(ptr->next != NULL){
if(ptr->next->data > n && ptr->data < n){
new->next = ptr->next;
ptr->next = new;
break;
}
ptr = ptr->next;
}
// insert at the end of list
if(ptr->next == NULL){
ptr->next = new;
}
return first;
}
void traverse(NODE *first){
NODE* ptr = first;
while(ptr != NULL){
printf("%d\n", ptr->data);
ptr = ptr->next;
}
}
NODE* search(NODE *first, int n){
NODE* ptr = first;
while(ptr != NULL){
if(ptr->data == n){
printf("FOUND %d\n!", n);
return ptr;
}
ptr = ptr->next;
}
}
int main(){
NODE* first = NULL;
NODE* this = NULL;
first = insert(first, 7);
first = insert(first, 10);
first = insert(first, 11);
first = insert(first, 1);
first = insert(first, 3);
first = insert(first, 5);
first = insert(first, 22);
first = insert(first, 23);
first = insert(first, 24);
first = insert(first, 125);
pop(&first);
}
【问题讨论】:
-
请在您的问题中添加
NODE的声明以及调用pop的代码。 -
“内存泄漏错误”到底是什么意思?
-
我看到的一个问题是,如果
first只包含一条记录,while(ptr->next->next != NULL)会导致段错误。 -
ptr->next->next在您没有检查ptr->next的NULL时总是错误。注意你已经发布了两个不同的pop()函数。 -
*first != NULL && first!= NULL应该相反。你可以访问first,即使它是NULL。