C++ force new[] to not allocate 4 additional bytes

Viewed 294

I'm writing my own memory system in C++ (for performance reasons, additional debugging information, and so that I can allocate memory that is 16-byte aligned), and I am encountering an issue with new[].

It seems that calling new[] results in an allocation of an additional 4 bytes indicating the number of elements in the array, which throws off the alignment of all subsequent objects. So my question is this:

Is there any way to turn off the usage of these 4 extra bytes with a compiler flag, pragma declaration, etc.?

Here's an example:

// Matrix class has to be 16-byte aligned
Matrix* transforms = new( matrixHeap, ALIGN_16, __FILE__, __LINE__ ) Matrix[31];
transforms[0] = Matrix::Identity;

When looking in the Visual Studio 2013 debugger, I see these values:

returned by new    0x0F468840
transforms         0x0F468844

Finally, I take a peek at the raw memory, and I see this:

0x0F468840   1F 00 00 00
0x0F468844   01 00 00 00

The memory at ******40 is not the first value in transforms[0] as expected. Rather, it contains the value 31. This means that the matrices are only 4-byte aligned. Is there any way to turn off that array size business so that the first byte of transforms[0] ends up in the address returned by new[]?

Here is the important bits of my operator new[]:

void* operator new[] ( size_t size, Heap* heap, uint32_t alignment, char* file, int lineNumber )
{
    size_t alignedSize = size + alignment - 1;
    void* unalignedPtr = heap->Allocate( alignedSize );
    void* alignedPtr = (void*) (((size_t) unalignedPtr + alignment - 1) & ~(alignment - 1));
    return alignedPtr;
}
1 Answers
Related