When do I have to free?
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开发者_JAVA百科 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 = first
are that you are transferring ownership, then second_free
should indeed call first_free
. (Although in this case, it may be appropriate to have a second_create_first
function, to keep things encapsulated.)
If you are not transferring ownership, then calling first_free
should be the responsibility of the client code.
Whatever semantics you choose, you should make things very clear in your documentation.
Since the user allocated first
, the user should free it.
It depends on wheter your second_new
function does allocate memory for his member b
or not. Allocation / deallocation should be symmetric.
Go for which ever approch you feel is more flexible.
If you think that the user has allocated the memory and user has to free.then let him do it in his own way.
If you think that you want to make a user's life easy then write a suitable free function and let him call it if he thinks he should call it.
The question also seems to be vague here since untill the whole requirement is presented the question cant be answered.
I prefer the approach of:
Whoever did the allocation, is responsible for deallocation.
精彩评论