[英]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.我将如何以及在何处放置 free() function 在这段代码中,以防止 memory 在我 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?或者至少为这个 malloc 写一个 free() function 的语法是什么?
It seems this function adds a new node to a list.似乎这个 function 向列表中添加了一个新节点。
The dynamically allocated memory for the list should be freed when the list is not needed any more as for example例如,当不再需要列表时,应释放为列表动态分配的 memory
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然后 function 被称为
clear( &head );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.