简体   繁体   中英

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.

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) , eg 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).

Pretty much all memory allocators (such as those on linux/win32) have an allocation header that proceeds the memory allocation (which includes info about the size of the allocation). On linux for example, you can look at the source for malloc, and that gives info about the stored header (and how to compute its size):

https://git.busybox.net/uClibc/tree/libc/stdlib/malloc/malloc.h#n106

As already mentioned in a comment, debug builds may also allocate additional bytes at either side of the allocation to guard against buffer overrun errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM