Talk:cpp/memory/align
I believe that the aligned_alloc example function is wrong. The problem is that while it increments the p value, it doesn't decrement the sz value. The C++11 Standard states that std::align "decreases space by the number of bytes used for alignment" whereas the example code assumes that std::align decreases the space by alignment + size.
I believe the fixed version of the example code should be like this (adding sz -= sizeof(T)):
T* aligned_alloc(std::size_t a = alignof(T))
{
if (std::align(a, sizeof(T), p, sz))
{
T* result = reinterpret_cast<T*>(p);
p = (char*)p + sizeof(T);
sz -= sizeof(T);
return result;
}
return nullptr;
}
As I write this I see that the Dinkumware version of std::align appears to be broken in a number of ways, so you don't want to use VC++ in order to test my proposed fix. Use gcc or clang instead.
- You're correct. I originally wrote the example, and used the clang version of std::align to obtain the sample output, but I forgot to pay attention to sz. Edited. --Cubbi 20:15, 6 June 2013 (PDT)
- See: N4660, 23.10.5 Align, [ Note: The function updates its ptr and space arguments so that it can be called repeatedly with possibly different alignment and size arguments for the same buffer. — end note ]
- Also, see example N3916, p. 7, "class FixedBufferResource : public std::pmr::memory_resource" (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3916.pdf) Serge3leo (talk) 05:20, 23 March 2020 (PDT)
I believe that the aligned_alloc example function is wrong. The problem is that reinterpret_cast<>() is not followed by std::launder(), thus causing undefined behavor in the calling code as soon as that code attempts accessing any member of the object returned by aligned_alloc(). 95.84.184.206 03:23, 31 October 2022 (PDT)