Advertisement

Dynamic array of struct containing __m128

Started by September 15, 2019 08:04 AM
4 comments, last by -Tau- 4 years, 12 months ago

My game keeps crashing and i have no idea why. The worst thing is, it keeps crashing on different locations in the code. Sometimes it just freezes and the music keeps playing, sometimes it straight out closes. This happens most when i try to end a level and sometimes when i try to load a level after it was closed. I managed to pinpoint the location of the crash to multiple places and one that stuck out was when i try to delete an array of struct containing XMVECTOR.

From what i heard before i understand that i can't just new and delete structs that contain __m128 where XMVECTOR is typedef of this. I found a solution for this by redefining operators new and delete for these structs:


struct afKeyFrame
{
	XMVECTOR vector;
	float time;

	void* operator new(size_t i)
	{
		return _mm_malloc(i, 16);
	}

	void* operator new[](size_t i)
	{
		return _mm_malloc(i, 16);
	}

	void operator delete(void* p)
	{
		_mm_free(p);
	}

	void operator delete[](void* p)
	{
		_mm_free(p);
	}
};

// also later in the code

aPosition = new afKeyFrame[mNumPositionKeys];

SAFE_DELETE_ARRAY(aPosition);

My question is: Is this the correct way create dynamic arrays for structs that contain __m128 variables?

I think you need __declspec(align(16)), but I'm not sure. Or you could just use XMFLOAT3 or XMFLOAT4 and save you the hassle of overloading the new and delete operators.

Advertisement

In theory, the default operator new should correctly align all allocations, so you should not need your own operator new.  If this is not happening, then it's possible that the compiler does not know about the correct alignment of XMVECTOR, which could cause it to put insufficient padding in your struct.

Check if sizeof(afKeyFrame) is a multiple of 16.  If it's not, either declare it as "struct alignas(16) afKeyFrame" or, if alignas doesn't work, manually add padding members until you get a multiple of 16.

1 hour ago, a light breeze said:

In theory, the default operator new should correctly align all allocations

In theory it aligns them so it works with standard data types like int and double, but not necessarily to 16 bytes. Especially for 32-bit programs it might only use 8-byte alignment.

As I said, using XMFLOAT* data types is much easier and usually not a significant performance hit.

So made one test and it looks like this is not the problem. sizeof(afKeyFrame) is 32 and i can create and delete an array of afKeyFrame multiple times without any issue.

This topic is closed to new replies.

Advertisement