gpt4 book ai didi

c - c中的可用内存问题删除了链表中的某些值

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

typedef struct node_t { int val; struct node_t *next; } node;   

node *deleteNumber(node *node, int i) {
while (node && node->val == i) {
node = node->next;
}
n = node;
p = node;
if (n == NULL)
return NULL;
n = n->next;
while (n) {
if (n->val == i)
p->next = n->next;
else
p = p->next;
n = n->next;
}
return node;
}

我有一个问题,如何释放链表中已删除节点的内存。上面的函数,node是我要操作的链表,int是我要删除的值。谢谢!

它目前导致 valgrind 错误,我不知道从哪里开始。我试过 free(n,p) 但这没有帮助

> ==1618== 
> ==1618== HEAP SUMMARY:
> ==1618== in use at exit: 192 bytes in 12 blocks
> ==1618== total heap usage: 12 allocs, 0 frees, 192 bytes allocated
> ==1618==
> ==1618== LEAK SUMMARY:
> ==1618== definitely lost: 128 bytes in 8 blocks
> ==1618== indirectly lost: 48 bytes in 3 blocks
> ==1618== possibly lost: 0 bytes in 0 blocks
> ==1618== still reachable: 16 bytes in 1 blocks
> ==1618== suppressed: 0 bytes in 0 blocks
> ==1618== Rerun with --leak-check=full to see details of leaked memory
> ==1618==
> ==1618== For counts of detected and suppressed errors, rerun with: -v
> ==1618== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

最佳答案

我不完全确定你的 deleteNumber 应该做什么,但以下版本释放列表中与数字匹配的所有元素,返回指向剩余列表第一个元素的指针(如果列表现在为空,则为 NULL)。

#include <stdlib.h>

typedef struct node_t { int val; struct node_t *next; } node;

node* deleteNumber(node* start, int i) {
node* n = start;
node* p = NULL;
node* t;

while (n) {
t = n;
n = n->next;
if (t->val == i) {
if (p)
p->next = n;
else
start = n;
free(t);
} else {
p = t;
}
}
return start;
}

下面是一些用于测试上述内容的附加函数:

#include <stdio.h>

/* append number to list, returning start of list */
node* addNumber(node* start, int i) {
node* t;

t = malloc(sizeof(*t));
if (t == NULL)
return start;
t->next = NULL;
t->val = i;
if (start) {
node* p = start;

while (p->next)
p = p->next;
p->next = t;
} else {
start = t;
}
return start;
}

/* print elements of list */
void printList(node* list) {
while (list) {
printf(" %d", list->val);
list = list->next;
}
}

/* free whole list */
void deleteList(node* list) {
node* t;

while (list) {
t = list;
list = list->next;
free(t);
}
}

int main(void) {
const int test[] = { 2, 3, 4, 2, 5 };
node* start = NULL;
int i;

/* construct a list */
for (i = 0; i < sizeof(test) / sizeof(test[0]); i++)
start = addNumber(start, test[i]);
/* report initial list contents */
printf("Before:");
printList(start);
printf("\n");
/* delete a number from the list */
start = deleteNumber(start, 2);
/* report updated list contents */
printf("After:");
printList(start);
printf("\n");
/* delete remaining elements of the list to appease Valgrind */
deleteList(start);
return 0;
}

上面的代码应该没有任何Valgrind错误。

关于c - c中的可用内存问题删除了链表中的某些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54446500/

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