Comment by Karellen

Comment by Karellen 2 days ago

1 reply

Surely that's only the case if realloc() actually resizes and copies on every call? Which it normally doesn't?

I thought that most implementations of realloc() would often "round up" internally to a larger size allocation, maybe power-of-two, maybe page size, or something? So if you ask for 20 bytes, the internal bookkeeping sets aside 32, or 4096, or whatever. And then if you realloc to 24 bytes, realloc will just note that the new allocation fits in the amount its reserved for you and return the same buffer again with no copying?

o11c 2 days ago

Some implementations might round up to encourage reuse:

* memory-checking allocators never do.

* purely-size-based allocators always do.

* extent-based allocators try to, but this easily fails if you're doing two interleaving allocations.

* the mmap fallback does only if allowing the kernel to choose addresses rather than keeping virtual addresses together, unless you happen to be on a kernel that allows not leaving a hole

Given that there's approximately zero overhead to do it right, just do it right (you don't need to store capacity, just compute it deterministically from the size).