我一直在测试自己的代码,以了解耗尽堆或空闲存储上的内存需要多少已分配内存。但是,除非我的代码在测试中是错误的,否则我会在堆上可以放置多少内存方面得到完全不同的结果。
我正在测试2个不同的程序。第一个程序在堆上创建矢量对象。第二个程序在堆上创建整数对象。
这是我的代码:
#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 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);
}
}
}
此代码在出现bad_alloc
错误之前的最终输出是:“堆上有511 MB”
两种代码中的最终输出彼此差异很大。我对免费商店有误解吗?我以为两个输出结果都差不多。
[C0很有可能。
如果pointer returned by new
on your platform is 16-byte aligned为new
字节,则意味着每int
您将获得4个字节并使12个字节不可用。