Heap array allocates 4 extra bytes if class has destructor

I’m new to C++ and I’ve been playing around with memory allocation lately. I have found out that when you declare a class with a destructor, like so:

class B
{
public:
    ~B() { }
};

And then create a heap array of it like so:

B* result = new B[8];

The allocator allocates 12 bytes but when I remove the destructor, it only allocates 8 bytes. This is how I’m measuring the allocation:

size_t allocated = 0;

void* operator new(size_t size)
{
    allocated += size;
    return malloc(size);
}
void deallocate(B* array, size_t size)
{
    delete[] array;
    allocated -= size * sizeof(B);
}

Of course I have to call deallocate manually while the new operator is called automatically.

I have found this problem while working with an std::string* and I realised that the deallocator worked fine with a int* but not with the former.

Does anyone know why that happens and more importantly: How to detect these programatically at runtime?

Thanks in advance.

Source: Windows Questions C++

LEAVE A COMMENT