Let’s say I have the following structures:
typedef struct first {
int a;
int b;
char *c;
} *first_t;
typedef struct second {
char *a;
first_t b;
} *second_t;
The user does something like this:
first_t first = first_new();
second_t second = second_new();
second->b = first;
Where first_new and second_new allocate memory.
I want to write a free function for the second_t structure.
I think I would have to let the user the responsability to free his first_t structure. Is it correct ? or do I have to write something like:
void second_free(second_t second) {
free(second->a);
first_free(second->b);
free(second);
}
It depends. What are the semantics of your code?
If the semantics of
second->b = firstare that you are transferring ownership, thensecond_freeshould indeed callfirst_free. (Although in this case, it may be appropriate to have asecond_create_firstfunction, to keep things encapsulated.)If you are not transferring ownership, then calling
first_freeshould be the responsibility of the client code.Whatever semantics you choose, you should make things very clear in your documentation.