简体   繁体   English

记忆去哪儿了?

[英]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) .我认为nNode * sizeof(Node) pm2-pm1近似于nNode * sizeof(Node) But it turns out pm2-pm1 is much larger than nNode *sizeof(Node) .但事实证明pm2-pm1nNode *sizeof(Node)大得多。 Where did the memory go?记忆去哪儿了? I suspect sizeof(Node) does not reflect the correct memory usage.我怀疑sizeof(Node)没有反映正确的内存使用情况。

I have tested on both Windows and linux.我已经在 Windows 和 linux 上进行了测试。 Final conclusion is Node * p = new Node;最终结论是Node * p = new Node; will allocate a memory larger than sizeof(Node) where Node is a class.将分配大于sizeof(Node)的内存,其中Node是一个类。

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.分配大小:您的 C++ 实现可能以大于sizeof(Node)单位分配内存,例如限制它所做的簿记量。
  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.对齐:分配器可能有返回地址与 2 的某个最小幂对齐的策略。同样,这可能会在一定程度上简化其实现。
  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).它当然符合语言规范(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).几乎所有的内存分配器(例如 linux/win32 上的那些)都有一个分配头来进行内存分配(其中包括有关分配大小的信息)。 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):例如,在 linux 上,您可以查看 malloc 的源代码,其中提供了有关存储的标头(以及如何计算其大小)的信息:

https://git.busybox.net/uClibc/tree/libc/stdlib/malloc/malloc.h#n106 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.正如评论中已经提到的,调试版本还可以在分配的任一侧分配额外的字节,以防止缓冲区溢出错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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