簡體   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