2 ms·
> When an application frees an object it always has the original, requested allocation size on hand. This is false in general. If it's true in your library tha
by kazinator 3y ago
> When an application frees an object it always has the original, requested allocation size on hand.
This is false in general. If it's true in your library that you have this old size on hand, then design the allocator callbacks with old-size arguments in free and realloc. If it's not convenient, then don't design those arguments in.
Most of the time, the allocator implementation will the be the default one via malloc and free, where the size is not required, so you're making the caller calculate or retrieve a value that is thrown away before the allocator is called.
There are situations in which a program would have to calculate the size in order to recover it. A trivial example is when a string is duplicated (as with the POSIX strdup function).
If the free function required the original request size, we would have to free the string using free(str, strlen(str) + 1) rather than just free(str).
Another example is when we have a header structure followed by a flexible array member. We can't just free(obj) but something like free(obj, offsetof(obj_t, array) + sizeof(obj->array[0]) * obj->nelems).
The allocated size could be stored in an extra field, but that's not something required when the allocator is malloc/free.