【发布时间】:2014-02-18 20:32:20
【问题描述】:
只是在这里修改 C。我刚刚运行了 valgrind,结果发现我的程序中有内存泄漏,即使我释放了我分配的内存。我错过了什么?
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”。
-
为什么不包括 valgrind 输出?
-
在 stack_destroy 中,而不是 temp 调用它 Node* next;然后下一个 = S->tos->下一个;然后 s->tos = 下一个;这样你就不会引用释放的内存,尽管这不是你的问题
-
因为 valgrind 在 VM 中。无法复制输出
标签: c memory-leaks valgrind