여기에서 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
in stack_destroy, 임시 호출 대신 Node * next; then next = S-> tos-> next; then s-> tos = next; 그런 식으로 당신은 free'd 메모리를 참조하지 않습니다. 이것은 당신의 문제가 아닙니다. –