【发布时间】:2021-12-04 00:31:21
【问题描述】:
当我运行程序时,它可以工作,除非我删除了一个相当大的数字,例如 100 或更大,每当我远程输入任何与该数字一样大的东西时,我都会在出现错误后得到堆使用。终端说它是由insert() 中的第 53 行引起的,即这一行,tail->next = newNode;。我知道将头指针和尾指针作为全局变量并不是最好的编写方法,但是一旦我让它工作,我会改变它。
void insert(int nData) {
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node)+10);
newNode->data = nData;
newNode->next = NULL;
if(checkDuplicates(nData)==1){
return;
}else{
if(head == NULL){
head = newNode;
tail = newNode;
}
else {
tail->next = newNode;
tail = newNode;
}
}
}
void delete(int n){
if(head -> data==n){
struct Node *tempHead = head;
head= head -> next;
free(tempHead);
return;
} else{
struct Node *current = head;
struct Node *prev = NULL;
while(current!=NULL&¤t->data!=n){
prev = current;
current = current -> next;
}
if(current==NULL) return;
prev->next = current->next;
free(current);
}
}
【问题讨论】:
-
+10是干什么用的? -
您应该在分配新节点之前检查重复项。否则你有内存泄漏。
-
我在发布的代码中看不到任何可能导致释放后使用错误的内容。但也许你还有其他代码可以释放节点?或者代码中的其他一些错误会破坏堆,这是一个副作用。尝试使用
valgrind运行您的程序。 -
@Kush Patel 如果您不想在列表中有重复项,请构建一个排序列表。
标签: c linked-list heap-memory free singly-linked-list