<p><strong>Problem</strong></p>

<p><code>XMMATRIX</code> and <code>XMVECTOR</code> (which use <a href="https://msdn.microsoft.com/en-us/library/ayeb3ayc.aspx" rel="nofollow noreferrer"><code>__m128</code></a> under the hood) require 16 byte alignment. The C++ compiler can automatically ensure this for <code>XMMATRIX</code> and <code>XMVECTOR</code> data allocated on the stack, but can't ensure this for <code>XMMATRIX</code> and <code>XMVECTOR</code> data allocated on the heap. </p>

<p>In your specific situation (referring to the RasterTek tutorial), three member variables of your <code>D3DClass</code> class are declared to be of type <code>XMMATRIX</code> and you construct one instance of this <code>D3DClass</code> class on the heap by using the default <code>operator new</code> (due to the absence of a custom one). Using the default <code>operator new</code> does not guarantee this 16 byte alignment. Even if your code would have run fine using the default <code>operator new</code>, you could still face this issue after adding some extra member variables in the future.</p>

<p><strong>Solution 1</strong></p>

<p>The most easy fix in this specific case, is to allocate your <code>D3DClass</code> class instances on the stack instead of on the heap. This, however, does not prevent you or future users of your code to allocate an instance on the stack instead. </p>

<p><strong>Solution2</strong></p>

<p>The programmers of the DirectXMath library advise the general programmer audience to use <code>XMMATRIX</code> and <code>XMVECTOR</code> for calculations only, and to not use them as containers for storing persistent data (i.e. class member variables). For the latter, they advise to use <code>XMFLOAT4</code>, <code>XMFLOAT4x4</code>, etc. The latter structs do not impose the 16 byte alignment restriction and their instances can simply be loaded in SIMD registers by using <code>XMLoadFloat4</code> for <code>XMVECTOR</code>, <code>XMLoadFloat4x4</code> for <code>XMMATRIX</code>, etc.</p>

<blockquote>
  <p>However, often it is easier and more compact to avoid using <code>XMVECTOR</code>
  or <code>XMMATRIX</code> directly in a class or structure. Instead, make use of the
  <code>XMFLOAT3</code>, <code>XMFLOAT4</code>, <code>XMFLOAT4X3</code>, <code>XMFLOAT4X4</code>, and so on, as members of
  your structure. Further, you can use the Vector Loading and Vector
  Storage functions to move the data efficiently into <code>XMVECTOR</code> or
  <code>XMMATRIX</code> local variables, perform computations, and store the results.
  There are also streaming functions (<code>XMVector3TransformStream</code>,
  <code>XMVector4TransformStream</code>, and so on) that efficiently operate directly
  on arrays of these data types.</p>
</blockquote>

<p><strong>Solution 3</strong></p>

<p>Ensure the 16 byte alignment by overwriting <code>operator new</code>/<code>operator delete</code>, <code>operator new[]</code>/<code>operator delete[]</code>. We declare a template class which does allow heap allocation with arbitrary alignment restrictions:</p>

<pre><code>#include &lt;malloc.h&gt;

inline void *AllocAligned(size_t size, size_t alignment = 16) noexcept {
    return _aligned_malloc(size, alignment);
}

inline void FreeAligned(void *ptr) noexcept {
    if (!ptr) {
        return;
    }

    _aligned_free(ptr);
}

template&lt; typename DataT &gt;
struct AlignedData {

public:

    static void *operator new(size_t size) {
        const size_t alignment = __alignof(DataT);

        // __declspec(align) on DataT is required
        static_assert(alignment &gt; 8, 
            "AlignedData is only useful for types with &gt; 8 byte alignment.");

        void * const ptr = AllocAligned(size, alignment);
        if (!ptr) {
            throw std::bad_alloc();
        }

        return ptr;
    }

    static void operator delete(void *ptr) noexcept {
        FreeAligned(ptr);
    }

    static void *operator new[](size_t size) {
        return operator new(size);
    }

    static void operator delete[](void *ptr) noexcept {
        operator delete(ptr);
    }
};
</code></pre>

<p>This code snippet is based on the <a href="https://github.com/Microsoft/DirectXTK" rel="nofollow noreferrer">DirectXTK</a> and is also included in my own <a href="https://github.com/matt77hias/MAGE/blob/master/MAGE/MAGE/src/memory/allocation.hpp" rel="nofollow noreferrer">codebase</a> (including documentation).</p>

<p>This data structure can now be used as follows:</p>

<pre><code>__declspec(align(16)) struct Transform final : public AlignedData&lt; Transform &gt; {
    XMMATRIX m_transform;
}
</code></pre>

<p>A Transform structure can now be allocated on the heap with 16 byte alignment, since our custom <code>operator new</code> will now be invoked:</p>

<pre><code>Transform *transform = new Transform();
</code></pre>

<p>If you use instances of the <code>Transform</code> struct as member variables in other structs of classes, the alignment restrictions remain of course. So instead of having only alignment restrictions for <code>XMVECTOR</code> and <code>XMMATRIX</code>, you will have now alignment restrictions for <code>XMVECTOR</code>, <code>XMMATRIX</code> and <code>Transform</code>.</p>

<p><strong>Smart Pointer Pitfalls</strong></p>

<p>Be careful if you use <code>std::shared_ptr</code> and especially <code>std::make_shared</code>. The latter allocates the data block together with the control block without using customly defined allocators such as our custom <code>operator new</code>.</p>

<p>This means that this method will not work:</p>

<pre><code>template&lt; typename T, typename... ConstructorArgsT &gt;
inline std::shared_ptr&lt; T &gt; MakeShared(ConstructorArgsT&amp;&amp;... args) {
    return std::make_shared&lt; T &gt;(std::forward&lt; ConstructorArgsT &gt;(args)...);
}
</code></pre>

<p>but you should rather use an explicit invocation of <code>operator new</code> (which is also the case for <code>std::make_unique</code>):</p>

<pre><code>template&lt; typename T, typename... ConstructorArgsT &gt;
inline std::shared_ptr&lt; T &gt; MakeAllocatedShared(ConstructorArgsT&amp;&amp;... args) {
    return std::shared_ptr&lt; T &gt;(new T(std::forward&lt; ConstructorArgsT &gt;(args)...));
}
</code></pre>

<p><code>std::unique_ptr</code> and especially <code>std::make_unique</code> will work as intended since the latter explicitly calls <code>operator new</code> (due to the absence of a control block).</p>

<p><strong>RasterTek</strong></p>

<p><a href="http://www.rastertek.com/tutdx11s2.html" rel="nofollow noreferrer">RasterTek's second series of D3D11 tutorials</a> is a subset of <a href="http://www.rastertek.com/tutdx11.html" rel="nofollow noreferrer">RasterTek's first series of D3D11 tutorials</a> with the minor difference that the latter uses the obsolete <code>D3DXMath</code>. The <a href="https://blogs.msdn.microsoft.com/chuckw/2013/08/20/living-without-d3dx/" rel="nofollow noreferrer">transition</a> is from D3DXMath to DirectXMath is actually pretty straightforward. Therefore, it can be interesting to take a look at the first series as well (which I ported to <code>Visual Studio 2017</code>, run fine in both <code>Debug</code> and <code>Release</code> configurations, and can be founded as well in this <a href="https://github.com/matt77hias/RasterTek" rel="nofollow noreferrer">repository</a>).</p>

<p>If you want to stick to <code>DirectXMath</code>, you can also take a look at the D3D11 tutorials of Microsoft itself (<a href="https://code.msdn.microsoft.com/windowsdesktop/Direct3D-Tutorial-Win32-829979ef" rel="nofollow noreferrer">explanation</a> + <a href="https://github.com/walbourn/directx-sdk-samples/tree/master/Direct3D11Tutorials" rel="nofollow noreferrer">code</a>). (I also created a <a href="https://github.com/matt77hias/Direct3D-11-Projects" rel="nofollow noreferrer">repository</a> with some code refactors of these tutorials).</p>

CC BY-SA 3.0
2017-10-01T20:37:04.210Z
You can, however, make smart pointers work by specializing `std::allocator` for any aligned data type. This will also allow you to put your stuff into standard library containers, which is not a particularly rare use-case. Basically whenever you overload `new/delete` you should always remember to make your own allocator (or better, specialize the standard allocator). But Solution 2 might still be the most headache-free anyway.
Christian Rau
CC BY-SA 3.0
2017-09-29T17:18:24.943Z
2017-10-01T18:33:39.773Z
2017-10-01T18:33:39.773Z
Matthias
<p>I've been trying to build a simple DirectX renderer from the ground up (was an OpenGL guy before but i figure it's good to know different APIs). I've been following the guide at rastertek.com to learn how to get the basics up and running.</p>
<p>I got as far as <a href="http://www.rastertek.com/dx11s2tut03.html" rel="nofollow noreferrer">this lesson</a>, following the guide verbatim except for variable names, and ran into a really weird bug. The renderer class contains 3 XMMatrix instances, world, perspective and orthographic, but trying to initialize them would crash my application - it ran fine once i commented out these lines :</p>
<pre><code>m_projMat = XMMatrixPerspectiveFovLH(fov, aspect, nearplane, farplane);
m_orthoMat = XMMatrixOrthographicLH(width, height, nearplane, farplane);
m_worldMat = XMMatrixIdentity();
</code></pre>
<p>At first i thought it was the dreaded SIMD alignment issue, but I'm compiling 64-bit so that should be taken care of. After a bit more tinkering i found out the ortho and world matrices were fine, it was just the projection matrix that was causing problems. Assigning to this matrix with the other XMMatrix... functions also works ok.
So:</p>
<pre><code>m_projMat = XMMatrixPerspectiveFovLH(fov, aspect, nearplane, farplane); 
</code></pre>
<p>fails, but:</p>
<pre><code>m_projMat = XMMatrixPerspectiveLH(fov*aspect*nearplane, fov*nearplane, nearplane, farplane); 
</code></pre>
<p>works! The right-handed version also fails. Also, the failure only happens in release mode, not in debug. I'm using Visual Studio 2015 community and the SDKs that installed with it.</p>
<p>Has anyone else encountered this bug, or have any idea what's going on here?</p>

CC BY-SA 3.0
2017-09-29T16:37:51.593Z
You could try using the latest version of DirectXMath available at [Github](https://github.com/Microsoft/DirectXMath) and see if the problem persists.
Matthias
CC BY-SA 3.0
2017-09-29T16:39:27.067Z
Is there actually some info at compile or runtime about the crash?
Matthias
CC BY-SA 3.0
2017-10-28T13:26:26.260Z
Did my answer solved your question?
Matthias
CC BY-SA 3.0
2017-10-31T04:06:20.703Z
Yeah thanks, I've got it working now. I upgraded to the latest version of directx math and copied the source directly from Rastertek (second series). Still confused about what the bug actually was... Not alignment, AFAICT, since compiling 64-bit forces 16-byte heap alignment. And the other matrix methods worked fine and produced valid results. Possibly a subtle bug in my own copy of the code. Going forward, I think I'll work with Microsoft's own DirectX tutorials since these seem to work well out of the box with a minimum of hassle.
russ
<directx11>
XMMatrixPerspectiveFovLH is broken?
russ
# XMMatrixPerspectiveFovLH is broken?

(Asked by: username_0 on 2017-09-12)

I've been trying to build a simple DirectX renderer from the ground up (was an OpenGL guy before but i figure it's good to know different APIs). I've been following the guide at rastertek.com to learn how to get the basics up and running.

I got as far as [this lesson](http://www.rastertek.com/dx11s2tut03.html), following the guide verbatim except for variable names, and ran into a really weird bug. The renderer class contains 3 XMMatrix instances, world, perspective and orthographic, but trying to initialize them would crash my application - it ran fine once i commented out these lines :

```
m_projMat = XMMatrixPerspectiveFovLH(fov, aspect, nearplane, farplane);
m_orthoMat = XMMatrixOrthographicLH(width, height, nearplane, farplane);
m_worldMat = XMMatrixIdentity();

```

At first i thought it was the dreaded SIMD alignment issue, but I'm compiling 64-bit so that should be taken care of. After a bit more tinkering i found out the ortho and world matrices were fine, it was just the projection matrix that was causing problems. Assigning to this matrix with the other XMMatrix... functions also works ok.
So:

```
m_projMat = XMMatrixPerspectiveFovLH(fov, aspect, nearplane, farplane); 

```

fails, but:

```
m_projMat = XMMatrixPerspectiveLH(fov*aspect*nearplane, fov*nearplane, nearplane, farplane); 

```

works! The right-handed version also fails. Also, the failure only happens in release mode, not in debug. I'm using Visual Studio 2015 community and the SDKs that installed with it.

Has anyone else encountered this bug, or have any idea what's going on here?

**Tags:** directx11

> **Comments:**
> **username_1**: You could try using the latest version of DirectXMath available at [Github](https://github.com/Microsoft/DirectXMath) and see if the problem persists.  
> **username_1**: Is there actually some info at compile or runtime about the crash?  
> **username_1**: Did my answer solved your question?  
> **username_0**: Yeah thanks, I've got it working now. I upgraded to the latest version of directx math and copied the source directly from Rastertek (second series). Still confused about what the bug actually was... Not alignment, AFAICT, since compiling 64-bit forces 16-byte heap alignment. And the other matrix methods worked fine and produced valid results. Possibly a subtle bug in my own copy of the code. Going forward, I think I'll work with Microsoft's own DirectX tutorials since these seem to work well out of the box with a minimum of hassle.  

---

## 1 answers

### Answer by username_1 on 2017-09-29. Score: 1 | Accepted answer

**Problem**

`XMMATRIX` and `XMVECTOR` (which use [`__m128`](https://msdn.microsoft.com/en-us/library/ayeb3ayc.aspx) under the hood) require 16 byte alignment. The C++ compiler can automatically ensure this for `XMMATRIX` and `XMVECTOR` data allocated on the stack, but can't ensure this for `XMMATRIX` and `XMVECTOR` data allocated on the heap.

In your specific situation (referring to the RasterTek tutorial), three member variables of your `D3DClass` class are declared to be of type `XMMATRIX` and you construct one instance of this `D3DClass` class on the heap by using the default `operator new` (due to the absence of a custom one). Using the default `operator new` does not guarantee this 16 byte alignment. Even if your code would have run fine using the default `operator new`, you could still face this issue after adding some extra member variables in the future.

**Solution 1**

The most easy fix in this specific case, is to allocate your `D3DClass` class instances on the stack instead of on the heap. This, however, does not prevent you or future users of your code to allocate an instance on the stack instead.

**Solution2**

The programmers of the DirectXMath library advise the general programmer audience to use `XMMATRIX` and `XMVECTOR` for calculations only, and to not use them as containers for storing persistent data (i.e. class member variables). For the latter, they advise to use `XMFLOAT4`, `XMFLOAT4x4`, etc. The latter structs do not impose the 16 byte alignment restriction and their instances can simply be loaded in SIMD registers by using `XMLoadFloat4` for `XMVECTOR`, `XMLoadFloat4x4` for `XMMATRIX`, etc.

> However, often it is easier and more compact to avoid using `XMVECTOR`
> or `XMMATRIX` directly in a class or structure. Instead, make use of the
> `XMFLOAT3`, `XMFLOAT4`, `XMFLOAT4X3`, `XMFLOAT4X4`, and so on, as members of
> your structure. Further, you can use the Vector Loading and Vector
> Storage functions to move the data efficiently into `XMVECTOR` or
> `XMMATRIX` local variables, perform computations, and store the results.
> There are also streaming functions (`XMVector3TransformStream`,
> `XMVector4TransformStream`, and so on) that efficiently operate directly
> on arrays of these data types.

**Solution 3**

Ensure the 16 byte alignment by overwriting `operator new`/`operator delete`, `operator new[]`/`operator delete[]`. We declare a template class which does allow heap allocation with arbitrary alignment restrictions:

```
#include <malloc.h>

inline void *AllocAligned(size_t size, size_t alignment = 16) noexcept {
    return _aligned_malloc(size, alignment);
}

inline void FreeAligned(void *ptr) noexcept {
    if (!ptr) {
        return;
    }

    _aligned_free(ptr);
}

template< typename DataT >
struct AlignedData {

public:

    static void *operator new(size_t size) {
        const size_t alignment = __alignof(DataT);

        // __declspec(align) on DataT is required
        static_assert(alignment > 8, 
            "AlignedData is only useful for types with > 8 byte alignment.");

        void * const ptr = AllocAligned(size, alignment);
        if (!ptr) {
            throw std::bad_alloc();
        }

        return ptr;
    }

    static void operator delete(void *ptr) noexcept {
        FreeAligned(ptr);
    }

    static void *operator new[](size_t size) {
        return operator new(size);
    }

    static void operator delete[](void *ptr) noexcept {
        operator delete(ptr);
    }
};

```

This code snippet is based on the [DirectXTK](https://github.com/Microsoft/DirectXTK) and is also included in my own [codebase](https://github.com/matt77hias/MAGE/blob/master/MAGE/MAGE/src/memory/allocation.hpp) (including documentation).

This data structure can now be used as follows:

```
__declspec(align(16)) struct Transform final : public AlignedData< Transform > {
    XMMATRIX m_transform;
}

```

A Transform structure can now be allocated on the heap with 16 byte alignment, since our custom `operator new` will now be invoked:

```
Transform *transform = new Transform();

```

If you use instances of the `Transform` struct as member variables in other structs of classes, the alignment restrictions remain of course. So instead of having only alignment restrictions for `XMVECTOR` and `XMMATRIX`, you will have now alignment restrictions for `XMVECTOR`, `XMMATRIX` and `Transform`.

**Smart Pointer Pitfalls**

Be careful if you use `std::shared_ptr` and especially `std::make_shared`. The latter allocates the data block together with the control block without using customly defined allocators such as our custom `operator new`.

This means that this method will not work:

```
template< typename T, typename... ConstructorArgsT >
inline std::shared_ptr< T > MakeShared(ConstructorArgsT&&... args) {
    return std::make_shared< T >(std::forward< ConstructorArgsT >(args)...);
}

```

but you should rather use an explicit invocation of `operator new` (which is also the case for `std::make_unique`):

```
template< typename T, typename... ConstructorArgsT >
inline std::shared_ptr< T > MakeAllocatedShared(ConstructorArgsT&&... args) {
    return std::shared_ptr< T >(new T(std::forward< ConstructorArgsT >(args)...));
}

```

`std::unique_ptr` and especially `std::make_unique` will work as intended since the latter explicitly calls `operator new` (due to the absence of a control block).

**RasterTek**

[RasterTek's second series of D3D11 tutorials](http://www.rastertek.com/tutdx11s2.html) is a subset of [RasterTek's first series of D3D11 tutorials](http://www.rastertek.com/tutdx11.html) with the minor difference that the latter uses the obsolete `D3DXMath`. The [transition](https://blogs.msdn.microsoft.com/chuckw/2013/08/20/living-without-d3dx/) is from D3DXMath to DirectXMath is actually pretty straightforward. Therefore, it can be interesting to take a look at the first series as well (which I ported to `Visual Studio 2017`, run fine in both `Debug` and `Release` configurations, and can be founded as well in this [repository](https://github.com/matt77hias/RasterTek)).

If you want to stick to `DirectXMath`, you can also take a look at the D3D11 tutorials of Microsoft itself ([explanation](https://code.msdn.microsoft.com/windowsdesktop/Direct3D-Tutorial-Win32-829979ef) + [code](https://github.com/walbourn/directx-sdk-samples/tree/master/Direct3D11Tutorials)). (I also created a [repository](https://github.com/matt77hias/Direct3D-11-Projects) with some code refactors of these tutorials).

> **Comments:**
> **username_2**: You can, however, make smart pointers work by specializing `std::allocator` for any aligned data type. This will also allow you to put your stuff into standard library containers, which is not a particularly rare use-case. Basically whenever you overload `new/delete` you should always remember to make your own allocator (or better, specialize the standard allocator). But Solution 2 might still be the most headache-free anyway.  

---

