# Memory alignment with xnamath / Directx11

This topic is 2446 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi,

Just a little problem that I got. Suppose I have.

class foo
{
float a;
short b;
char c;
Whatever whatever;
...
XMMATRIX matworld_;
XMMATRIX matProj_;
XMMATRIX matView_;
};

Now I allocate a foo object on the heap with new. When I try to use any operation on my matrices (e.g. XMMatrixIdentity()), I sometimes have a violation access crash. I'm pretty sure this is because the matrices are not 16 bit aligned, because when I use global variables it works. The only solution I have found to settle this problem (untested though;)) is to use pointers on the matrices or on a struct of all 3 of them and use align_malloc. Is there any better way to do this ?

Thank you,

Joedassin

##### Share on other sites
If you are going to use new, you need to tell the compiler to align the members correctly, via __declspec(align()) or __attribute__((align())), depending on your compiler.
its also good practice (see intels optimization manuals) to have the biggest variables first along with those that have specialized alignment requirements, this makes sure everything is aligned correctly, and it can also save you memory by removing useless padding (which makes things more cache friendly).

However, this doesn't fix the fact that the base allocation may be off (which is more than likely your problem), so I generally make sure the SIMD stuff is correctly aligned in the struct/class (be careful with vftables, they can throw it off) either with manual padding or alignment specifiers. Then use _mm_malloc along with an init method or placement new else one can use overloaded operator new/delete. alternatively you could alloc the matrices on their own using aligned_malloc/_mm_malloc, how this generally kills cache locality.

as an example:
__declspec(align(16)) class Tester { public: char throwitoff; __m128i pVec; public: virtual ~Tester() { } };This fixes internals alignment, but new might still give use poorly aligned pointers, so thats a bit useless, to fix this, we can (ab)use class specific new/delete:

__declspec(align(16)) class Tester { public: char throwitoff; __m128i pVec; public: virtual ~Tester() { } void* operator new(size_t i) { return _mm_malloc(i,16); } void operator delete(void* p) { _mm_free(p); } };now it passes alignment requirements on both members and the allocation.

1. 1
2. 2
Rutin
19
3. 3
4. 4
5. 5

• 14
• 12
• 9
• 12
• 37
• ### Forum Statistics

• Total Topics
631425
• Total Posts
3000015
×