我看到下面code,爲什麼我們沒有釋放一個結構的嵌入指針用C
/* stack.c */
typedef struct Stack *StackPtr;
struct Stack
{
int *mStack;
int mCurSize;
};
StackPtr StackCreate()
{
return (StackPtr) calloc(sizeof(struct Stack), 1);
}
void StackDestroy(StackPtr stack)
{
if (stack)
{
free(stack);
}
}
void StackPush(StackPtr stack, int val)
{
if (! stack)
return;
if (stack->mStack)
{
int newsize = stack->mCurSize + 1;
int *newptr = realloc(stack->mStack, sizeof(struct Stack)*newsize);
if (newptr)
{
stack->mStack = newptr;
stack->mStack[newsize-1] = val;
stack->mCurSize = newsize;
}
}
else
{
stack->mStack = malloc(sizeof(struct Stack));
if (stack->mStack)
{
stack->mStack[0] = val;
stack->mCurSize = 1;
}
}
}
int StackPop(StackPtr stack)
{
if (! StackIsEmpty(stack))
{
return stack->mStack[--stack->mCurSize];
}
return 0;
}
void StackDestroyMyWay(StackPtr stack) // This is my understanding
{
if (stack)
{
if (stack->mStack)
free(stack->mStack);
free(stack);
}
}
int StackIsEmpty(const StackPtr stack)
{
return stack == NULL || stack->mCurSize == 0;
}
/* main.c */
int main(int argc, char *argv[])
{
/* Create a new stack */
StackPtr stack = StackCreate();
int val;
/* push and pop a value to the stack */
printf("Empty: %d\n", StackIsEmpty(stack));
StackPush(stack, 10);
printf("Empty: %d\n", StackIsEmpty(stack));
val = StackPop(stack);
printf("Popped off: %d\n", val);
printf("Empty: %d\n", StackIsEmpty(stack));
/* clean up the stack */
StackDestroy(stack);
return 0;
}
問題>我假定原來StackDestory正確實現,但我不知道明白爲什麼我們不必明確地釋放stack->mStack
。
我認爲你的方式是正確的方法。鑑於你向我們展示了什麼,除非明確地釋放mStack纔會泄漏。 –
我認爲你必須和原始實現有內存泄漏。除非它在代碼中某處不顯示:) – 2011-12-06 16:47:49
我認爲'StackDestroyMyWay()'也是正確的。但請注意,[您不必在'free()'](http://stackoverflow.com/q/1912325/10077)之前檢查null。所以你可以說,'if(stack){free(stack-> mStack);自由(堆);}'。 –