我正在尝试在 C++ 中找到可以在堆栈、全局和堆内存上分配的最大内存。我在具有 32 GB 内存的 Linux 系统和具有 2 GB RAM 的 Mac 上尝试这个程序。
/* test to determine the maximum memory that could be allocated for static, heap and stack memory */
#include <iostream>
using namespace std;
//static/global
long double a[200000000];
int main()
{
//stack
long double b[999999999];
//heap
long double *c = new long double[3999999999];
cout << "Sizeof(long double) = " << sizeof(long double) << " bytes\n";
cout << "Allocated Global (Static) size of a = " << (double)((sizeof(a))/(double)(1024*1024*1024)) << " Gbytes \n";
cout << "Allocated Stack size of b = " << (double)((sizeof(b))/(double)(1024*1024*1024)) << " Gbytes \n";
cout << "Allocated Heap Size of c = " << (double)((3999999999 * sizeof(long double))/(double)(1024*1024*1024)) << " Gbytes \n";
delete[] c;
return 0;
}
结果(两者):
Sizeof(long double) = 16 bytes
Allocated Global (Static) size of a = 2.98023 Gbytes
Allocated Stack size of b = 14.9012 Gbytes
Allocated Heap Size of c = 59.6046 Gbytes
我正在使用 GCC 4.2.1。我的问题是:
为什么我的程序正在运行?我预计由于堆栈耗尽(Linux 中为 16 MB,Mac 中为 8 MB),程序应该会抛出一个错误。我看到了这个主题中提出的许多问题中的一些,但我无法从那里给出的答案中解决我的问题。