Namespaces
Variants
Views
Actions

Talk:cpp/memory/align

From cppreference.com

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)