I was trying out the code shown below:
class Example {
public:
Example(int val = 0) : m_val(val) { }
~Example() { }
void* operator new (std::size_t sz) {
std::cout << "Example created on the heap with size " << sz << std::endl;
return std::malloc(sz);
}
void* operator new[] (std::size_t sz) {
std::cout << "Example created on the heap with size " << sz << std::endl;
return std::malloc(sz);
}
void operator delete (void* ptr) noexcept {
std::cout << "Deleted from the heap" << std::endl;
std::free(ptr);
}
void operator delete[] (void* ptr) noexcept {
std::cout << "Deleted from the heap" << std::endl;
std::free(ptr);
}
private:
int m_val;
};
From main, I tried to test new[] operator by calling below snippet from main
Example* p_example = new Example[4];
The output which was expected is 16, i.e. 4 times the sizeof(int) (since the class has only a 4 byte m_val member variable). However the output on the terminal was:
Example created on the heap with size 24
Now, when I comment out the destructor of the class, the output comes out to be what one would expect for it. Thus output with commented destructor is:
Example created on the heap with size 16
I eliminated the possibility of an extra 8 bytes allocated for the vtable pointer by adding a virtual function. In this case, the total memory allocated was an extra of 8 bytes over the original (which was 24 bytes), so the 8 bytes of memory which were being allocated extra are still being allocated so I believe that this is not as a result of inheritance.
I'm not able to figure out where the extra 8 bytes are allocated in this particular example, so any hints on the same would be appreciated. I tried using gdb to debug and see if any extra variables were present somewhere, but I couldn't notice anything out of the ordinary. Thanks!