繁体   English   中英

我 go 如何释放这个 malloc 以防止在使用 valgrind 时出现任何 memory 泄漏

[英]How would I go about freeing this malloc in order to prevent any memory leaks when using valgrind

我将如何以及在何处放置 free() function 在这段代码中,以防止 memory 在我 valgrind 时泄漏。 (这只是一段更大的代码)

pizzaNode * AddTopping1 (char *s, pizzaNode * head) {

    pizzaNode * newPtr = (pizzaNode *)(malloc(sizeof(pizzaNode)));
    
    // set values of the new node
    strcpy(newPtr->topping, s);
    newPtr->next = NULL;
    
    // Add the topping to the beginning of the list:
    if (head == NULL)
    {
        head = newPtr;
    }
    else
    {
        newPtr->next = head;
        //head = newPtr;
    }

    
    return newPtr;  // newPtr is the new head now
}

或者至少为这个 malloc 写一个 free() function 的语法是什么?

似乎这个 function 向列表中添加了一个新节点。

例如,当不再需要列表时,应释放为列表动态分配的 memory

void clear( pizzaNode **head )
{
    while ( *head != NULL )
    {
        pizzaNode *current = *head;
        *head = ( *head )->next;
        free( current );  
    }
} 

如果在调用者中声明了一个指向头节点的指针,例如

pizzaNode *head = NULL;

然后 function 被称为

clear( &head );

暂无
暂无

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

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