0

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.

Xenoprimate
  • 7,691
  • 15
  • 58
  • 95
  • What does the `XMMATRIX` constructor do? – JAB Jun 19 '14 at 16:11
  • I'm not sure, it's part of DirectX. Unless you meant my usage of it, in which case it's just setting the 16 components of the matrix (I cut out the huge list of floats for brevity's sake). – Xenoprimate Jun 19 '14 at 16:13
  • 3
    Oh, actually, you might want to look at http://stackoverflow.com/a/15753540/138772 and its mention of alignment issues. – JAB Jun 19 '14 at 16:13

1 Answers1

1

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.

Chuck Walbourn
  • 38,259
  • 2
  • 58
  • 81