[英]Correctly freeing pointer to linked list
在拥有超过10年的使用垃圾收集语言的奢侈品后,我回到了C99,显然我在内存管理方面遇到了困难。
我有一个由堆栈项和类型Stack
组成的链表,该类型指向此列表的第一个元素的地址。
到目前为止,这是我的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct StackItem
{
int head;
struct StackItem* next;
} StackItem;
typedef StackItem** Stack;
StackItem* makeStackItem (int head)
{
StackItem* a = (StackItem*) malloc (sizeof (StackItem) );
a->head = head;
a->next = (StackItem*) 0;
return a;
}
Stack makeStack ()
{
Stack stack = (Stack) malloc (sizeof (StackItem*) );
*stack = (StackItem*) 0;
return stack;
}
void pushStack (StackItem* item, Stack stack)
{
item->next = *stack;
*stack = item;
}
void freeStack (Stack stack)
{
StackItem* current = *stack;
StackItem* next;
while (current != 0)
{
next = current->next;
free (current);
current = next;
}
free (stack);
}
int main ()
{
Stack stack = makeStack ();
for (int i = 0; i < 10; i++)
pushStack (makeStackItem (i), stack);
printf ("Here be dragons.\n");
freeStack (stack);
return 0;
}
我的问题是:
makeStack
和makeStackItem
的第一行是否合理且必要?
freeStack
的最后一行freeStack
合理且必要?
一旦main
返回,我是否释放了先前分配的所有内存?
如何查看我是否有内存泄漏?
提前非常感谢您。
makeStack和makeStackItem的第一行是否合理且必要? yes except for the casting malloc issue
freeStack的最后一行是否合理且必要? yes
一旦主返回,我是否释放了先前分配的所有内存? yes
如何查看我是否有内存泄漏? use valgrind
I would toss the casts of 0 too.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.