Home > Enterprise >  C the right way to free a struct
C the right way to free a struct

Time:12-09

Let's imagine that you want to free a linked list node which happens to be a struct which is the right way to do it to prevent memory leaks struct

struct node{
    int value;
    struct node *next;
};

my solutions:

free(node);

or

free(node->next);
free(node);

if none of these are correct please correct me with you answers
thanks :>

CodePudding user response:

If you have allocated memory using malloc, calloc and realloc free is the right way to free a strict.

These are dynamic memory allocation in C. So only if you have dynamically allocated memory using these operators then you can use the free.

CodePudding user response:

It depends on how the data was allocated. If it was all allocated by malloc then yes, you need to free individual struct pointer members to such data before freeing the struct as whole, in several steps.

  • Related