简体   繁体   English

如何释放链表?

[英]How to free a linked list?

I have created a linked list in a function and throughout the rest of the program I am accessing the list using a pointer. 我已经在一个函数中创建了一个链表,在程序的其余部分中,我都使用指针来访问链表。 Now how would I free this linked list at the end of my program? 现在如何在程序结束时释放此链接列表? Do I plainly use free(CircuitData) or do I have to run through the list freeing each node? 我是简单地使用free(CircuitData)还是必须遍历列表以释放每个节点? Writing this I'm thinking freeing each node is the obvious answer... 写这篇文章我想释放每个节点是显而易见的答案...

On a side note I'd also like to ask how to find out whether all memory allocated during a program is freed properly? 附带一提,我还想问一问如何找出在程序执行期间分配的所有内存是否正确释放?

 ListNodeType *CircuitData;
 CircuitData = NULL;
 ReadFile(&CircuitData, &numEl, &numNodes);


void ReadFile(ListNodeType **CircuitData, int *numEl, int *numNodes){

    ListNodeType *newPtr, *tempPtr;
    newPtr = malloc(sizeof(ListNodeType));
    *CircuitData = newPtr;
    newPtr->nextPtr = NULL;

    //MORE CODE

I would think of something like this: 我会想到这样的事情:

struct node
{
    int data;
    node* next;
} *head;

void deleteAllNodes(node* start)
{
    while (start != NULL)
    { 
        node* temp = start; 
        start = start -> next;
        free(temp);
    }
}

I think you can do something like this : 我认为您可以执行以下操作:

void freeFunction(ListNodeType *CircuitData)
{
    void *victim;

    while (CircuitData)
    {
        victim = CircuitData;
        CircuitData = CircuitData->next;
        free(victim);
    }
}

For every malloc you will need a free otherwise you will leak memory. 对于每个malloc您将需要一个free否则会泄漏内存。 One possible way to analyze your program to see if you don't have memory leaks is to use Valgrind . 分析程序以查看是否没有内存泄漏的一种可能方法是使用Valgrind

For your first question, yes, you should walk the list and free each node. 对于第一个问题,是的,您应该遍历列表并free每个节点。

The second question is a bit harder to answer. 第二个问题很难回答。 If you have an object in memory, but no way to access it, that's a memory leak. 如果您在内存中有一个对象,但无法访问它,则是内存泄漏。

There are tools you can use to analyze your memory pool. 您可以使用一些工具来分析内存池。 Check out valgrind: 查看valgrind:

http://valgrind.org/ http://valgrind.org/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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