Question

I have a class:

class CMatrix4f
{
public:
    CMatrix4f();

public:
     __declspec(align(16)) float m[16];
};

This class implements matrix operations with SSE, so m must be aligned for it to work. And it works most of the time, but sometimes I get segfault when executing SSE instructions like _mm_load_ps because m is not 16-bytes aligned. So far I can't understand in which cases it happens.

When I do CMatrix4f * dynamicMatrix = new CMatrix4f();, is dynamicMatrix.m guaranteed to be aligned?

If I have a class:

class MatrixWrapper {
public:
   MatrixWrapper();

   CMatrix4f _matrix;
};

And then do:

MatrixWrapper * dynamicMatrixWrapper = new MatrixWrapper();

Is dynamicMatrixWrapper._matrix.m guaranteed to be aligned?

I've read MSDN article on alignment, but it is unclear whether it works for dynamic allocation.

Was it helpful?

Solution

since __declspec(align(#)) is a compilation directive, creating the MatrixWrapper object with the new operator can result in unaligned memory on the heap. You may consider using _aligned_malloc and allocate memory dynamically, for example in the constructor, and then free it using _aligned_free in the destructor, by the way mixing static and dynamic allocation of object makes things more difficult.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top