Home > Net >  Freeing a struct within a struct in C
Freeing a struct within a struct in C

Time:04-25

So, I'm working in C and I'm allocating an array of type struct, and within that struct I'm also allocating another array of different struct.

typedef struct {
    char name[MAX_NAME   1];
    ITEM *items;
} database;

typedef struct {
    char name[NAME_MAX   1];
}ITEM;
database *array = (database*)malloc(n1 * sizeof(database));

array[i].items = (ITEM*)calloc(n2 * sizeof*(ITEM));

Does the command free(array); take care of freeing the whole thing, including the ITEM array I allocated within it?

CodePudding user response:

No, you need to free every single data allocation done by calloc() or malloc().

A few points
  • calloc(n2 * sizeof*(ITEM)); is completely wrong. You need write like this
array[i].items = calloc(n2, sizeof(ITEM));
  • You don't need to typecast the value returned from malloc() and calloc()
  • Always check whether heap-allocation was successful or not, by checking the pointer against NULL
  • struct ITEM should be declared before struct database, to avoid forward-declaration error
  • You need to free the resources using a loop which will iterate till n1
for (size_t i = 0; i < n1; i  )
{
    free(array[i].items);
}
free(array);
  • Related