c++ - 为什么我可以使用大缓冲区作为 vector ,但不能在 Windows 上使用 new?

标签 c++ arrays visual-c++ 64-bit

我使用的是 64 位 Windows 7 Pro 和 Visual Studio 2010 Pro。

我正在尝试分配和使用大于 4 GB 的缓冲区(用于高数据速率数据捕获)。

将缓冲区作为字节 vector 分配和写入工作正常。将缓冲区分配为字节数组工作正常,但写入该数组很快就会崩溃。 (最后打印的消息是“缓冲区已分配”。)

注释掉 vector 部分并不能解决问题。

以下是我的测试程序:

#include <iostream>
#include <vector>
#include <BaseTsd.h>

using namespace std;

int main() {
  const ULONG64 BUF_SIZE = 4 * 1024ULL * 1024ULL * 1024ULL;

  {
    vector<unsigned __int8> v(BUF_SIZE);
    cout << "vector allocated" << endl;
    for (ULONG64 i = 0; i < BUF_SIZE; ++i) {
      v[i] = 0xff;
    }
    cout << "vector written" << endl;
  }

  {
    unsigned __int8* buffer = new unsigned __int8[BUF_SIZE];
    cout << "buffer allocated" << endl;
    for (ULONG64 i = 0; i < BUF_SIZE; ++i) {
      buffer[i] = 0xff;
    }
    cout << "buffer written" << endl;
    delete[] buffer;
  }

  return 0;
}

更新:我相信这是一个编译器错误。看这里: http://connect.microsoft.com/VisualStudio/feedback/details/553756/invalid-check-for-maximum-array-size-in-x64-compiler-c2148

最佳答案

我刚刚尝试用 VS2010 Pro(64 位版本)编译给定的代码,编译器生成了一个 C2148 error对于 new 调用:

error C2148: total size of array must not exceed 0x7fffffff bytes

我在运行 vcvarsx86_amd64.bat 后从命令行编译它。似乎 limit given here也许以某种方式发挥作用。将 new 更改为 [BUF_SIZE-1] 允许它编译和运行(尽管它仍然大于那些链接中讨论的 0x7fffffff 数字)。

关于c++ - 为什么我可以使用大缓冲区作为 vector ,但不能在 Windows 上使用 new?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8580172/

相关文章:

c++17 聚合初始化

c++ - 非常基本的模板功能出现问题

c++ - Visual 2015 上的 std::get_time 不会在不正确的日期失败

c++ - 将对话框过程作为方法绑定(bind)到自定义类

c++ - 使用 libdxf 的段错误

c - 在 "negative"位置填写数组值

java - 如何将字符串转换为二维字符数组

c++ - "Right"解除分配 std::vector 对象的方法

c++ - Visual Studio : how to start up a project without the console window poping up

ios - 如何使用对象映射器 Swift 映射字典数组