Reputation: 489
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();
Upvotes: 8
Views: 11494
Reputation: 6834
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.].
Upvotes: 2
Reputation: 458
void *malloc(size_t size);
Here, you specify the size that needs to be allocated and what it returns is void* which you can cast it later to the required pointer type.
foo *pFoo = new foo();
Here, the size is decided by the new itself by going through the object layout. Also note that the new operator calls the constructor of foo. If you need it the same you did it for malloc, do it like below:
void * ptr = new size_t[size];
Not even satisfied..! You can overload new operator the way you want. Google for overloading new operator.
Upvotes: -3
Reputation: 114559
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.
Upvotes: 8