[libc-commits] [libc] [libc] Add aligned_alloc (PR #96586)

Paul Kirth via libc-commits libc-commits at lists.llvm.org
Mon Jul 1 12:27:03 PDT 2024


ilovepi wrote:

> > Something I'm realizing should either be tested, or documented as a limitation, is the case where the caller aligns the allocation themselves, by bumping the allocation size up and then aligning the pointer to get the correct alignment. I've seen that pattern in many codebases, even in the Rust core libraries. If the allocator isn't able to free those correctly, we should make sure that is written down somewhere as a limitation. If it is supported, we should test it. I know that usage is often incorrect, but I've seen it enough to know that people will do that, even if `aligned_alloc` is available.
> 
> Is the case you mention something like this?
> 
> ```
> char *ptr = (char *)malloc(size + desired_alignment);
> uintptr_t ptr_int = reinterpret_cast<uintptr_t>(ptr);
> if (ptr_int % desired_alignment != 0) {
>   ptr += (desired_alignment - (ptr_int % desired_alignment));
> }
> ...
> free(ptr);  // ptr may not be the exact same value as returned by malloc
> ```

Yeah, that's about right. I also did some looking at the projects where I'd seen this and it seems like at least a few of the codebases that used to do this no longer do (Rust compiler and a few networking libraries), so maybe this is less important than I thought? Probably fine to just document that as some kind of abuse of the API and call it a day, better still if there's something to quote from the standard.

https://github.com/llvm/llvm-project/pull/96586


More information about the libc-commits mailing list