I have link list whose node structure is given below
struct node
{
char *p;
struct node *next;
}*start;
Now we char *p is pointer to memory location which allocated by malloc call.Similarly the whole is also allocated using malloc. Now would like to free the space occupied by both the malloc call ,something like this below
main()
{
struct node *tmp;
tmp=malloc(sizeof(struct node));
tmp->next=NULL;
tmp->p=malloc(2*sizeof(int));
free(tmp->p);
free(tmp);
}
Is it the right way to free memory or something is required here?
This is the right way but don’t forget to assign pointers to NULL after using free otherwise the pointers will become dangling pointers.
Use them like this –
free(tmp->p);
tmp->p = NULL;