这里只是修改C.我只是跑了valgrind,事实证明我的程序中有内存泄漏,即使我释放了我分配的内存。我错过了什么?堆栈在C:为什么我有内存泄漏?
stack.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;
}
也许它太明显了,但我敢确定你只需要改变你的“stack_destroy”。在保存“S-> tos-> next”之前,您可以释放“S-> tos”。 – MrHappyAsthma
你为什么不包含valgrind输出? – hyde
在stack_destroy中,而不是temp调用它Node * next;那么next = S-> tos-> next;那么s-> tos = next;这样你就不会引用free'd内存,尽管这不是你的问题 –