问题是您使用带符号的 32 位变量来描述无符号的 64 位数字。
使用“size_t”而不是“int”来保存存储计数。这与您打算存储的内容无关,而与您需要多少数量无关。
#include <iostream>
int main(int /*argc*/, const char** /*argv*/)
{
int units = 2;
// 32-bit signed, i.e. 31-bit numbers.
int intSize = units * 1024 * 1024 * 1024;
// 64-bit values (ULL suffix)
size_t sizetSize = units * 1024ULL * 1024ULL * 1024ULL;
std::cout << "intSize = " << intSize << ", sizetSize = " << sizetSize << std::endl;
try {
unsigned short* intAlloc = new unsigned short[intSize];
std::cout << "intAlloc = " << intAlloc << std::endl;
delete [] intAlloc;
} catch (std::bad_alloc) {
std::cout << "intAlloc failed (std::bad_alloc)" << std::endl;
}
try {
unsigned short* sizetAlloc = new unsigned short[sizetSize];
std::cout << "sizetAlloc = " << sizetAlloc << std::endl;
delete [] sizetAlloc;
} catch (std::bad_alloc) {
std::cout << "sizetAlloc failed (std::bad_alloc)" << std::endl;
}
return 0;
}
输出(g++ -m64 -o test test.cpp 在 Mint 15 64 位下使用 g++ 4.7.3 在具有 4Gb 内存的虚拟机上)
intSize = -2147483648,sizetSize = 2147483648
intAlloc 失败
sizetAlloc = 0x7f55affff010