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

via libc-commits libc-commits at lists.llvm.org
Thu Jun 27 15:00:50 PDT 2024


PiJoules 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
```

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


More information about the libc-commits mailing list