为什么我可以使用一个大的缓冲区作为一个矢量,而不是与Windows上的新

Why can I use a large buffer as a vector but not with new on Windows?

本文关键字:一个 Windows 缓冲区 可以使 我可以 为什么      更新时间:2023-10-16

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

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

将缓冲区作为字节向量进行分配和写入工作正常。将缓冲区分配为字节数组工作得很好,但是写入该数组很快就会崩溃。(最后打印的消息是"buffer allocated")

注释掉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位版本)编译给定的代码,编译器为new调用产生了C2148错误:

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

我在运行vcvarsx86_amd64.bat之后从命令行编译了它。这里给出的极限似乎在某种程度上起作用了。将new更改为[BUF_SIZE-1]允许它编译和运行(尽管这仍然大于那些链接中讨论的0x7fffffff数)。

相关文章: