Search code examples
cpointersstructfreedynamic-arrays

Arrays of struct in c


struct a {
    int a;
    int b; 
};

struct a* ptr = NULL;

In main

ptr = malloc(5 * sizeof(struct a )); 
//assume is 5 is from user 

Assign values to ptr[0].a and ptr[0].b, similarly to all 5 block

free(ptr);

Is free (ptr) enough to free all arrays of struct? Or should i free explicitly? If so, how? Thanks.


Solution

  • You need to free whatever is returned by any memory management function. For allocations that are nested you need to do it reverse order of the way they are allocated. (Typical example would be creation of jagged array)

     void free(void *ptr);
    

    From 7.22.3.2p2

    The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

    In your case free(ptr) would be enough to free the dynamically allocated memory. If it contained some pointer variable to which we assigned address of dynamically allocated memory then you would need to free then first and then this ptr variable.