1

I have a previously allocated chunk of memory that I want to interpret in-place as a struct. How could I determine the memory address within the chunk that has the friendliest alignment for the struct?

Just need to know the mechanism for determining what byte boundary a given struct would work best within, basically.

// psuedo-code

struct Object{
    int    theseMembersCould;
    double beAnything;
    char   itsJustData[69];
}

// a chunk of previously allocated memory that I want to use
std::vector<uint8> block;
block.resize(1024);

uint32 byteBoundary = ????;  // <-- this is what I want to discover

// math to get the nearest addr on the boundary (assumes byteBoundary will be POW2)
uint32 alignmentOffset= (byteBoundary - (block.data() & byteBoundary-1u)) & byteBoundary-1u;

Object * obj = new (block.data() + alignmentOffset) Object;
obj->itsJustData = "used as if it were a normal object beyond this point";
Anne Quinn
  • 12,609
  • 8
  • 54
  • 101
  • C++11 and later, look up the `alignof` operator, `alignas` specifier, and `std::aligned_storage` type trait. Plenty of information, with examples, on various C++ reference sites. In combination, they can most likely be used to achieve what you need. – Peter Dec 28 '18 at 16:24

2 Answers2

3

The alignof operator will tell you the alignment required by a type. For example const auto byteBoundary = alignof(Object);.

Consider using std::aligned_storage if you need to create aligned raw memory. You will also need to use placement new to properly being the lifetime of the Object you are trying to use block as.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
  • @AnneQuinn Remember that by using `new`, your object will not be automatically destroyed. But using `delete` would also be problematic, as you are not suppose to release the memory like you would normally. You need to manually call your object's destructor when you are done with it with `obj->~Object();`. – François Andrieux Dec 28 '18 at 16:34
2

Firs off, you attempted use of reinterpret_cast is incorrect, as it leads to undefined behavior due to strict aliasing rule violation. Instead, you should use placement new.

To properly align your struct, you can use std::align together with std::alignof.

SergeyA
  • 61,605
  • 5
  • 78
  • 137