'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?



Solution 1:[1]

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 );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1