Kyl*_*yle 6 c++ memory-management out-of-memory
我一直在测试自己的一些代码,以查看耗尽堆或空闲存储上的内存需要多少已分配内存。但是,除非我的代码在测试中是错误的,否则我会在堆上可以放置多少内存方面得到完全不同的结果。
我正在测试两个不同的程序。第一个程序在堆上创建矢量对象。第二个程序在堆上创建整数对象。
这是我的代码:
#include <vector>
#include <stdio.h>
int main()
{
long long unsigned bytes = 0;
unsigned megabytes = 0;
for (long long unsigned i = 0; ; i++) {
std::vector<int>* pt1 = new std::vector<int>(100000,10);
bytes += sizeof(*pt1);
bytes += pt1->size() * sizeof(pt1->at(0));
megabytes = bytes / 1000000;
if (i >= 1000 && i % 1000 == 0) {
printf("There are %d megabytes on the heap\n", megabytes);
}
}
}
Run Code Online (Sandbox Code Playgroud)
出现bad_alloc错误之前,此代码的最终输出是:“堆上有2000 MB”
在第二个程序中:
#include <stdio.h>
int main()
{
long long unsigned bytes = 0;
unsigned megabytes = 0;
for (long long unsigned i = 0; ; i++) {
int* pt1 = new int(10);
bytes += sizeof(*pt1);
megabytes = bytes / 1000000;
if (i >= 100000 && i % 100000 == 0) {
printf("There are %d megabytes on the heap\n", megabytes);
}
}
}
Run Code Online (Sandbox Code Playgroud)
出现bad_alloc错误之前,此代码的最终输出是:“堆上有511 MB”
这两个程序的最终输出有很大的不同。我对免费商店有误解吗?我认为这两个结果大致相同。
如果int是4字节,这意味着对于每个new int(10)字节,您将获得 4 个字节,并使 12 个字节无法使用。
仅此一点就可以解释从小分配中获取 500MB 可用空间与从大分配中获取 2000MB 可用空间之间的差异。
最重要的是,跟踪分配的块(至少是它们的大小以及它们是否空闲或正在使用)会产生开销。这与系统的内存分配器非常相关,但也会产生每次分配的开销。有关 的分配器的说明,请参阅https://sourceware.org/glibc/wiki/MallocInternals中的“什么是块” 。glibc