I'm having some trouble setting two variables of type XMMATRIX** in a function. The function prototype looks like this:
bool ViewportFactory::CreateViewport(CanvasHandle* canvasHandlePtr, ViewportHandle** outViewportHandlePtr, DirectX::XMMATRIX** outProjectionMatrix, DirectX::XMMATRIX** outViewMatrix)
Then, later on in the function definition, I have the following two lines:
*outProjectionMatrix = new DirectX::XMMATRIX(0.0f, 0.1f, /* ... */, 3.3f);
*outViewMatrix = new DirectX::XMMATRIX(0.0f, 0.1f, /* ... */, 3.3f);
However, in a Win32 build with optimisations turned on, those lines give me an access violation.
It's hard to reason about exactly where the problem is with optimisations turned on, but if I change those lines to set the values to nullptr
, then the problem goes away.
This is indeed an alignment problem. new DirectX::XMMATRIX in a 32-bit program is only 8-byte aligned, and XMMATRIX must be 16-byte aligned.
You can either use __aligned_malloc/__aliged_free instead of new or use the XMFLOAT4X4 type instead. Or rather than allocating individual XMMATRIX values from the heap, use stack-allocated XMMATRIX instead which will be properly aligned since XMMATRIX is marked as __declspec(align(16)).
This is covered in the DirectXMath Programmer's Guide on MSDN. It's not a long document, and it contains lots of advice.