[英]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-pm1
比nNode *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:由于您尚未指定正在运行的平台,因此有以下几种可能性:
sizeof(Node)
, eg to limit the amount of book-keeping it does.sizeof(Node)
单位分配内存,例如限制它所做的簿记量。 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.