繁体   English   中英

正确释放指向链表的指针

[英]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;
}

我的问题是:

  1. makeStackmakeStackItem的第一行是否合理且必要?

  2. freeStack的最后一行freeStack合理且必要?

  3. 一旦main返回,我是否释放了先前分配的所有内存?

  4. 如何查看我是否有内存泄漏?

提前非常感谢您。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM