简体   繁体   中英

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

How and where would I put a free() function in this piece of code in order to prevent memory leaks when I valgrind. (This is just a piece of a larger code)

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
}

Or at least what is the syntax to write a free() function for this malloc?

It seems this function adds a new node to a list.

The dynamically allocated memory for the list should be freed when the list is not needed any more as for example

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

If in the caller you declared a pointer to the head node like for example

pizzaNode *head = NULL;

then the function is called like

clear( &head );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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