How to determine the size of the memory allocated by C++ new operator. ?
In C, malloc has the syntax:
void *malloc(size_t size);
here we know what size we are allocating.
but in C++ how can we determine what size is allocated when we do memory allocation as below. I am interested to know how new
determines the size that needs to be allocated.
foo *pFoo = new foo();
The C++ operator new
allocates sizeof(T)
bytes (either using the standard global allocator ::operator new(size_t)
or a custom allocator for T
if it has been defined).
After that it calls the constructors (first bases and other sub-objects and then the constructor for T
itself).
It's however possible and even common that some of the constructors called allocate more memory.
For test purposes, you can override global operator new to find out how much is allocated:
void* operator new(size_t size)
{
std::cout << "allocating " << size << std::endl;
return malloc(size);
}
[ Really not recommended for production code, but it can be done - read up very carefully.].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With