How to free a struct that contains only pointers

wonnie picture wonnie · Feb 6, 2011 · Viewed 25.3k times · Source

I have a struct which you see below:

typedef struct _List {
    Person *person; // pointer for people list
    DoList *do; // Kinda timer, for checking list in some intervals
} List;

Are there any need to free this struct? If so, how can i free it?

Answer

par picture par · Feb 6, 2011

You have to free the struct if you allocated it dynamically. You have to free its members before deallocating the struct if you allocated the members dynamically and don't have a reference to them anywhere else.

Here are some examples:

void freeNotRequiredHere() {
    List            nonDynamicList;
    Person          nonDynamicPerson;
    DoList          nonDynamicDoList;

    nonDynamicList.person = &nonDynamicPerson;
    nonDynamicList.do = &nonDynamicDoList;
}


void freeRequiredForStructListOnly() {
    List            *dynamicList;
    Person          nonDynamicPerson;
    DoList          nonDynamicDoList;

    dynamicList = (List *) malloc( sizeof(struct List) );

    dynamicList->person = &nonDynamicPerson;
    dynamicList->do = &nonDynamicDoList;

    free( dynamicList );
}


void freeRequiredForStructListAndPersonOnly() {
    List            *dynamicList;
    Person          *dynamicPerson;
    DoList          nonDynamicDoList;

    dynamicList = (List *) malloc( sizeof(struct List) );
    dynamicPerson = (Person *) malloc( sizeof(Person) );

    dynamicList->person = dynamicPerson;
    dynamicList->do = &nonDynamicDoList;

    free( dynamicPerson );
    free( dynamicList );
}


void freeRequiredForStructListAndPersonOnly( DoList *notSureDoList ) {
    List            *dynamicList;
    Person          *dynamicPerson;

    dynamicList = (List *) malloc( sizeof(struct List) );
    dynamicPerson = (Person *) malloc( sizeof(Person) );

    dynamicList->person = dynamicPerson;
    dynamicList->do = notSureDoList;

    // maybe notSureDoList was allocated with malloc(),
    // maybe it is a non-dynamic stack variable.
    // the calling function should deal with free()'ing notSureDoList

    free( dynamicPerson );
    free( dynamicList );
}