Array size error x64 process

后端 未结 2 1638
长情又很酷
长情又很酷 2021-01-04 19:06

I was checking how big of an array can I create on a X64 application, my understanding was that I can create arrays bigger than 2^31 on X64 process but I\'m getting a compil

相关标签:
2条回答
  • 2021-01-04 19:09

    This appears to be a defect in the 32-bit cross compiler for x64 targets. The Microsoft Connect link posted by icabod in the comments above addresses this particular issue. Unfortunately the bug's status has been set to Closed - Won't Fix.

    The following code snippets will fail to compile using the 32-bit cross compiler for x64:

    char* p = new char[(size_t)1 << 32];
    

    and

    const size_t sz = (size_t)1 << 32;
    char* p = new char[sz];
    

    Both of the above will fail with the error message error C2148: total size of array must not exceed 0x7fffffff bytes when compiled with the 32-bit cross compiler for x64. Unfortunately, Visual Studio does launch the 32-bit compiler even when run on a 64-bit version of Windows, targetting x64.

    The following workarounds can be applied:

    • Compiling the code using the native 64-bit compiler for x64 from the command line.
    • Changing the code to either of the following:

      size_t sz = (size_t)1 << 32;  // sz is non-const
      char* p = new char[sz];
      

      or

      std::vector<char> v( (size_t)1 << 32 );
      

    The bug is still present in Visual Studio 2012, and all workarounds still apply.

    0 讨论(0)
  • 2021-01-04 19:20

    The compiler is likely trying to optimize since your ARRSIZE value is a constant. And then it hits its own static initialization limit. You could probably just take out the "const" keyword and it will work.

    If not, something like this will likely work.

    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;
    }
    
    0 讨论(0)
提交回复
热议问题