Collections-C icon indicating copy to clipboard operation
Collections-C copied to clipboard

Automatically free data when removing it from a container

Open srdja opened this issue 8 years ago • 4 comments

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

  • an optional operation
  • should not assume the same allocators are used for both data and the structure

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);

srdja avatar Apr 13 '16 22:04 srdja

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);

f2404 avatar Apr 14 '16 07:04 f2404

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.

srdja avatar Apr 14 '16 11:04 srdja

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

f2404 avatar Apr 14 '16 11:04 f2404

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?

yangxingpping avatar Jan 19 '20 06:01 yangxingpping