Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine size of Memory allocated by new operator in C++

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();
like image 860
Nrupatunga Avatar asked Apr 14 '14 05:04

Nrupatunga


2 Answers

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.

like image 75
6502 Avatar answered Nov 09 '22 23:11

6502


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.].

like image 31
Keith Avatar answered Nov 09 '22 23:11

Keith