Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which cases can __declspec( align( # ) ) not work?

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.

like image 536
Violet Giraffe Avatar asked Jan 30 '26 11:01

Violet Giraffe


1 Answers

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.

like image 153
Jekyll Avatar answered Feb 01 '26 02:02

Jekyll



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!