by geocar · 4mo ago · 0 comments
If you can convince the caller to keep track of that metadata themselves you obviously don’t need to. That can be important.
Something I noticed is that _very often_ the code that is calling malloc(n) is keeping track of n somehow for its own reasons (bounds checking, grow/gap pointers, etc) so merging the value halves stack churn and it’s an easy win.
So, most likely, there are two sizes in reality: the size of your user data that you care about; and the size of the memory chunk in which your user data resides, that free() cares about. So, unless you're willing to go for an API like this, you can't rely on the consumer:
int* ptr_to_dest = NULL;
size_t size = 10 * sizeof(int);
size_t allocated = malloc(&ptr_to_dest, size);
if (allocated <= 0 || !ptr_to_dest) {
//handle allocation error
}
//... use ptr_to_dest, size
free(ptr_to_dest, allocated); //careful not to pass size here!> That's why C23 introduce free_sized
Is it? C23 still has free, so there’s no guarantee callers wil use free_sized, so the allocator still has to be able to obtain a block’s size from a pointer.
Or do I overlook something?
I think the only thing free_size adds is robustness. Allocators can check the passed in size with what they know and abort the program if they do not match. That can thwart some security issues.
likely it'd a be perf. hit in most cases. They'd have to copy to the tail end (likely) of the allocated area. Or the start and offset the pointer, they'd need to know the size of the metadata and account for that, including aligning it.Hence, the tail feels 'nicer'
It's possible to manually use mmap and forgo malloc entirely, rolling your own arena manager.