Search code examples
cmemoryreallocansi-c

C memory deallocation of array stored data structures


I am writing a C based library and I'm a little confused when it comes to using free() to deallocate blocks of memory... Essentially I have several similar structs defined this way:

typedef struct
{
    pthread_t thread_id;
    pthread_attr_t attr;
    void     *data;
    size_t stacksize = NULL;
} thread_info;

Where I essentially use realloc() to allocate memory for this structure and have an array point to it.

My question is, if I use:

free(my_array[thread_index]); 

Would the free() call deallocate memory used not just by the structure but all its data types within it, ie. the *thread_id*, attr, data, and stacksize will be deallocated as well or do I have to deallocate them individually then deallocate the structure from the array.

To me it would make sense that if I am using free() on such a structure all data contained within it will be deallocated and I wouldn't have to explicitly deallocate each struct attribute but I just want to make sure if that is the case.


Solution

  • For dynamically allocated "structures" (i.e. heirarchies of array's, struct's, etc), you need to call free on each pointer from "the bottom up". You can think of this operation as performing a depth-first traversal of a tree.

    The usual restrictions apply to variables that are pointers to memory on the stack, rather than the heap. For example, variables defined with type[n], char[n] = 'abc', etc vs. allocations from the heap using the *alloc family of functions. Also beware of cases where there are multiple pointers to the same address, calling free twice on these is a programming error (though not necessarily a segmentation fault).