Ori*_*iru 6 c++ windows visual-c++
我在Windows的x64模式下。在Visual Studio上使用MSVC进行编译。new当我这样做时,操作员似乎未按预期工作:
char* buf = new char[1LLU << 32];
Run Code Online (Sandbox Code Playgroud)
但是,如果我传入一个变量而不是直接输入大小,则它可以正常工作:
uint64_t sz = 1LLU << 32;
char* buf = new char[sz];
Run Code Online (Sandbox Code Playgroud)
查看汇编代码,编译器忽略了我提供的大小xor ecx, ecx,我相信只是将0传递给了new运算符。
这真令人困惑!我不知道标准中是否指定了一些规则?
ps char* buf = new char[1LLU << 31];可以正常工作。所以我认为它与我使用的整数大小有关。但是在文档中,请new接受size_tas参数,在x64上应为uint64_t。
VirtualAlloc()/ HeapAlloc()是比new本文更安全使用的好选择。
完整代码(请注意*尝试在Visual Studio中本地复制):
#include <iostream>
#include <cstdint>
int main()
{
char* ptr = new char[1LLU << 32];
memset(ptr, 0, sizeof(char) * (1LLU << 32)); //Access violation writing location...
}
Run Code Online (Sandbox Code Playgroud)
#include <iostream>
#include <cstdint>
int main()
{
uint64_t sz = 1LLU << 32;
char* ptr = new char[sz];
memset(ptr, 0, sizeof(char) * (1LLU << 32)); //no problem
}
Run Code Online (Sandbox Code Playgroud)
添加const到您的声明中:
const uint64_t sz = 1LLU << 32;
Run Code Online (Sandbox Code Playgroud)
你会得到同样的错误:
这是数组分配的“安全”MSVC 阈值,但由于您提供了非常量大小变量,编译器不会在编译时解析它。