Search code examples
cmallocfree

Free-ing an array of structs obtained through malloc


So I have this struct:

typedef struct type {
      int a;
      char* b;
} type;

In the main program, I make 2 arrays of these structs, and use malloc():

type *v;
type *w;
v=malloc(50*sizeof(type));
w=malloc(50*sizeof(type));

Now I if I want to free these arrays of structs is it correct to do:

free(v);
free(w);

?


Solution

  • It will be correct provided that you did not allocate memory for data member

    char* b;
    

    of elements of the arrays.

    Otherwise you need at first to free the memory pointed to by this data member and only then to free the original pointers.

    For example

    for ( size_t i = 0; i < 50; i++ ) free( v[i].b );
    free( v );
    

    Take into account that if this data member was initialized by the address of a string literal then you shall not free this memory because string literals have the static storage duration.