Search code examples
c++pointersmemorysizeof

where did the memory go?


class Node
{
//some member variables.
};
std::cout<<"size of the class is "<<sizeof(Node)<<"\n";
int pm1 =peakmemory();
std::cout<<"Peak memory before loop is "<< pm1<<"\n";
for(i=0; i< nNode; ++i)
{
  Node * p = new Node;
}
int pm2 =peakmemory();
std::cout<<"Peak memory after loop is "<< pm2<<"\n";

I thought pm2-pm1 approximates nNode * sizeof(Node). But it turns out pm2-pm1 is much larger than nNode *sizeof(Node). Where did the memory go? I suspect sizeof(Node) does not reflect the correct memory usage.

I have tested on both Windows and linux. Final conclusion is Node * p = new Node; will allocate a memory larger than sizeof(Node) where Node is a class.


Solution

  • Since you haven't specified what platform you're running on, here are a few possibilities:

    1. Allocation size: Your C++ implementation may be allocating memory in units which are larger than sizeof(Node), e.g. to limit the amount of book-keeping it does.
    2. Alignment: The allocator may have a policy of returning addresses aligned to some minimum power of 2. Again, this may simplify its implementation somewhat.
    3. Overhead: Some allocators, in addition to the memory you are using, have some padding with a fixed pattern to protect against memory corruption; or some meta-data used by the allocator.

    That is not to say this actually happens. But it could; it certainly agrees with the language specification (AFAICT).