gpt4 book ai didi

c - 内存泄漏链表

转载 作者:太空宇宙 更新时间:2023-11-04 08:04:40 24 4
gpt4 key购买 nike

我的 CS 类(class)作业有问题。我一直在和一个 friend 一起工作,我们已经确定我们的代码存在内存泄漏,但我们找不到问题所在。本质上,该代码应该创建一个包含 2-1000 数字的链表。然后,代码使用 deletemultiples 来删除非质数。它通过获取一个数字并删除链表中该数字的任何倍数来实现。当我们使用 valgrind 时,它返回内存泄漏。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

struct node{
int info;
struct node *next;
};

typedef struct node node;

node *inserthead(node *head, int a);
node *inserttail(node *head, int a);
node *deletemultiples(node *head, int a);
void printlist(node *head);
void freelist(node *head);

int main(){

node *head1 = NULL;
int i,j;
for(i = 2;i <= 1000;i++)
head1 = inserttail(head1,i);
for(i = 2; i <= 32; i++){
head1 = deletemultiples(head1,i);
}
printlist(head1);
freelist(head1);
}

node *inserthead(node *head, int a){
node *ptr;

ptr = (node*)malloc(sizeof(node));
ptr->info = a;
ptr->next = head;

return(ptr);
}

node *inserttail(node *head, int a){
node *ptr;
node *ptr2 = head;

ptr = (node*)malloc(sizeof(node));
ptr->info = a;
ptr->next = NULL;

if(head == NULL)
return(ptr);
else if (head->next == NULL){
head->next = ptr;
return(head);
}
while(head->next != NULL)
head = head->next;

head->next = ptr;
return(ptr2);
}

void printlist(node *head){
while(head!=NULL){
printf("%i ",head->info);
head = head->next;
}
printf("\n");
}

void freelist(node *head){
node *ptr = head;
while(head != NULL){
head = head->next;
free(ptr);
ptr = head;
}
}

node *deletemultiples(node *head, int a){
node *ptr = head, *temp = head;

while (ptr != NULL) {
if(ptr->info % a > 0){
ptr = ptr->next;
temp = temp->next;
}
else{
ptr = ptr->next;
temp->next = ptr;
}
}

return(head);

}

如果有人能帮助我们找出我们做错了什么,我们将不胜感激!

最佳答案

您的 deletemultiples() 函数永远不会释放它取消链接的节点,因此 freelist() 在遍历列表以删除它时永远不会到达它们。删除您删除的节点,方法与您在 freelist() 中所做的相同。

或者,您可以创建一个包含 1,000 个节点的数组(将这样的常量转换为符号名称是一个好习惯。)并将该数组中的节点作为弱引用进行链接和取消链接。当您销毁所有依赖它的列表时,您将在一次调用中释放整个数组。

感谢您在代码中查找内存泄漏。它会让你省去很多痛苦。

关于c - 内存泄漏链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43683615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com