memcpy和其他函数可以处理的缓冲区的最大大小是多少?这个实现依赖吗?这是否受到作为参数传入的大小(size_t)的限制?
我有以下代码:
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
typedef uint64_t Huge_num; // 8 bytes
typedef Huge_num * Huge_Arr; // Array of 8 byte elements
using namespace std;
// Function: Return a huge array
static Huge_Arr* requestMem(int n)
{
cout << "requesting :"
<< (sizeof(Huge_num)*n)/(1024*1024*1024)
<< "GB" << endl;
Huge_Arr *buff;
try {
buff = new Huge_Arr[n];
}
catch (bad_alloc){
cout << "Not enough mem!" << endl;
exit(-1);
}
return buff;
}
// Main
int main(){
for (int i=1; i< …Run Code Online (Sandbox Code Playgroud) 我正在尝试读取大小为 ~1.1GB 的 .dat 文件中包含的数据。因为我是在 16GB RAM 的机器上执行此操作,所以我认为将整个文件一次读入内存不会有问题,只有在处理它之后。
为此,我使用了slurp在这个 SO answer 中找到的函数。问题是代码有时(但并非总是)抛出 bad_alloc 异常。查看任务管理器,我发现总有至少 10GB 的可用内存可用,所以我不知道内存会是什么问题。
这是重现此错误的代码
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
ifstream file;
file.open("big_file.dat");
if(!file.is_open())
cerr << "The file was not found\n";
stringstream sstr;
sstr << file.rdbuf();
string text = sstr.str();
cout << "Successfully read file!\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
什么可能导致这个问题?避免它的最佳做法是什么?