gpt4 book ai didi

c - 堆栈在 C : why do i have memory leaks?

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

这里只是修改C。我刚刚运行了 valgrind,结果发现我的程序中有内存泄漏,即使我释放了我分配的内存。我错过了什么?

堆栈.c:

#include <stdlib.h>
#include <stdio.h>
#include "stack.h"

struct node {
int element;
Node *next;
};

struct stack {
Node *tos;
};

Stack *stack_create() {
Stack *S;
if ((S = (Stack *)malloc(sizeof(Stack))) != NULL)
S->tos = NULL;
return S;
}

void stack_destroy(Stack *S) {
Node *temp = S->tos;
while (S->tos != NULL) {
temp = S->tos;
free(S->tos);
S->tos = temp->next;
}
free(S);
}

void push(Stack *S, int element) {
Node *N;
if ((N = (Node *)malloc(sizeof(Node))) != NULL) {
N->element = element;
N->next = (S->tos == NULL) ? NULL : S->tos;
S->tos = N;
}
}

int pop(Stack *S) {
Node *tos = S->tos;
S->tos = tos->next;
return (int) tos->element;
}

int peek(Stack *S) {
return (int) S->tos->element;
}

void to_string(Stack *S) {
Node *cursor = S->tos;
while (cursor != NULL) {
printf("[%d] ", cursor->element);
cursor = cursor->next;
}
printf("\n");
}


int main()
{
Stack *S;

S = stack_create();

push(S, 5);
push(S, 6);
push(S, 4);
push(S, -55);

to_string(S);

printf("Pop %d\n", pop(S));
printf("Pop %d\n", pop(S));

to_string(S);

stack_destroy(S);

return 0;
}

enter image description here

最佳答案

实际问题是你的 Pop 杀死了节点,但它没有释放它

Node* node_destroy(Node* n)

Node* next;
if(n == NULL) return NULL;
next = n->next;
free(n);
return next;
}


int stack_pop(Stack *s) {
int element;
if(s == NULL || s->tos == NULL) return 0; // no really good result you can give
element = s->tos->element;
s->tos = node_destroy(s->tos);
return element;
}

那么你可以做

void stack_destroy(Stack *S) {
while (S->tos != NULL) {
s->tos = node_destroy(s->tos);
}
free(S);
}

关于c - 堆栈在 C : why do i have memory leaks?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21864671/

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