Reputation: 950
I have the following struct which I use to implement a priority queue
struct q_element
{
//Declaration of struct members
int element;
int priority;
struct q_element *next_element;
};
and I use a pointer to a struct 'cur' to start from the first item in the queue
struct q_element* cur = start_element;
and keep moving until I find the one I want to delete from list.
while (cur->priority!=max_priority)
cur = cur->next_element;
Does the following line of code actually free the struct? Because 'cur' is a pointer to the struct I wasn't completely sure.
free(cur);
Upvotes: 1
Views: 85
Reputation: 726499
You need to pass a pointer to free
, so free(cur)
is the way to go, assuming that the struct
itself has been allocated using malloc
/calloc
/realloc
. Specifically, if you allocated your curr
in the automatic memory (i.e. on the stack) you are not supposed to call free
on it.
It looks like q_element
is part of a linked list. Freeing the struct
itself will not free other struct
s pointed to by it, so if you'd like to free
the struct
along with its tail, you need to write a loop.
Finally, when you free
memory pointed to by some pointer in your program, it is a very good idea to assign NULL
to the pointer that you free
d to avoid accidental double-freeing and undefined behavior on accessing freed memory.
Upvotes: 3