我一直在测试自己的代码,看看需要多少分配内存才能耗尽堆内存或自由存储。但是,除非我的代码测试有误,否则我得到的结果完全不同,无法确定可以放入堆上的内存量。
我正在测试两个不同的程序。第一个程序在堆上创建向量对象。第二个程序在堆上创建整数对象。
以下是我的代码:
#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);
}
}
}
这段代码在出现
bad_alloc
错误前的最终输出结果是:“堆上有2000兆字节”。在第二个程序中:#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);
}
}
}
在遇到bad_alloc
错误之前,此代码的最终输出为:“堆上有511兆字节”。
两个程序的最终输出差别很大。我是否对自由存储区有什么误解?我认为两种结果应该差不多。
10
初始化。 - RuslanMB
的结果可能会有误,因为除非在你的机器上ints
至少占用10个字节
,否则任何小于一百万的字节数都会使初始计算为0。当然,我是在谈论第一个向量示例,但我认为你在第二个示例中失去了更多的精度。 - smac89