Cod*_*777 9 c++ arrays winapi visual-studio-2010
我正在检查在X64应用程序上可以创建多大的数组,我的理解是我可以在X64进程上创建大于2 ^ 31的数组但是我在VS2010编译器上遇到编译错误,代码如下
const size_t ARRSIZE = size_t(1)<<32;
int main()
{
char *cp = new char[ARRSIZE];
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在目标x64平台上的VS2010上给编译器错误"错误C2148:数组的总大小不得超过0x7fffffff字节",我可以创建upto(size_t(1)<< 32 - 1);
我有链接器 - >高级 - >目标机器是Machinex64.链接器 - >系统 - >启用大地址为是(不确定这是否真的重要).pc中存在的分页文件\物理Ram是否重要?(我确定它是一个64位应用程序,因为如果我删除该行并且只有char*cp;它是8字节.)我错过了一些设置吗?
这似乎是x64目标的32位交叉编译器中的缺陷.icabod在上面的评论中发布的Microsoft Connect链接解决了这个特殊问题.不幸的是,bug的状态已经设置为Closed - Will not Fix.
对于x64,使用32位交叉编译器无法编译以下代码片段:
char* p = new char[(size_t)1 << 32];
Run Code Online (Sandbox Code Playgroud)
和
const size_t sz = (size_t)1 << 32;
char* p = new char[sz];
Run Code Online (Sandbox Code Playgroud)
error C2148: total size of array must not exceed 0x7fffffff bytes
当使用32位交叉编译器编译x64时,上述两种方法都将失败并显示错误消息.不幸的是,Visual Studio确实启动了32位编译器,即使在64位版本的Windows上运行,目标是x64.
可以应用以下变通方法:
将代码更改为以下任一项:
size_t sz = (size_t)1 << 32; // sz is non-const
char* p = new char[sz];
Run Code Online (Sandbox Code Playgroud)
要么
std::vector<char> v( (size_t)1 << 32 );
Run Code Online (Sandbox Code Playgroud)该错误仍然存在于Visual Studio 2012中,并且所有解决方法仍然适用.
编译器可能会尝试优化,因为您的 ARRSIZE 值是一个常量。然后它达到了它自己的静态初始化限制。您可能只需取出“const”关键字就可以了。
如果没有,类似的事情可能会起作用。
extern size_t GetArraySize();
int main()
{
size_t allocationsize = GetArraySize();
char *cp = new char[allocationsize];
return 0;
}
size_t GetArraySize()
{
// compile time assert to validate that size_t can hold a 64-bit value
char compile_time_assert_64_bit[(sizeof(size_t) == 8)?1:-1];
size_t allocsize = 0x100000000UL; // 64-bit literal
return allocsize;
}
Run Code Online (Sandbox Code Playgroud)