srdja / Collections-C

A library of generic data structures for the C language.
http://srdja.github.io/Collections-C
GNU Lesser General Public License v3.0
2.84k stars 326 forks source link

Automatically free data when removing it from a container #45

Open srdja opened 8 years ago

srdja commented 8 years ago

There should be a more convenient way to free data after it's removed from a container and it should be:

I suggest adding a callback to remove type functions so that instead of:

void *e;
container_remove_at(c, 3, &e);
free(e);

we could write something like this:

container_remove_at(c, 3, NULL, free);
f2404 commented 8 years ago

Is the callback required? I mean, the conf structure already contains a pointer to 'free' function ('mem_free'). I think a boolean flag could be enough, i.e. container_remove_at(c, 3, NULL, true);

srdja commented 8 years ago

Well mem_free and others are used by the structure internaly. The thing is that we can't guarantee that the data was allocated using the same allocators as was the structure. To illustrate, imagine having some sort of wrappers for free and malloc, with which we allocate the data to, for example, track the memory consumption, but use regular free and malloc for the structure because its memory consumption isn't of interest. You can see that in this case it would actually be incorrect to let the structure use its internal free to deallocate the data.

And when you think about it, the container shouldn't really need care about how the data is created or destroyed because it's really only there to organize it. So letting the user specify an optional callback when the data is being removed is I think the best way to go about this. The callback could also be any type of function not just a free which would add some flexibility.

f2404 commented 8 years ago

Ah, I understand what you're saying. Yes, you are right, specifying the callback function is proper way to go.

yangxingpping commented 4 years ago

I'm also have the same issue, Like hashtable_remove(table, key, out). hashtable key and value are both alloc by malloc before call hashtable_add(table, key, value), but I cann't get key pointer after call hashtable_remove(...). When I try to set config->mem_free callback, but I found callback not only call with TableEntry, but alse with table->buckets and table in hashtable_destroy(), and I can't distingush what type in callback mem_free with a void pointer paramer. May be hashtable_remove(...) need add one more parameter used to return the key pointer store in the hashtable?