c++ - 创建4GB std::string时分配错误

标签 c++ bad-alloc

我正在使用多重解析器发送http POST请求,并且我需要发送一个大文件(4Go)。
但是,当我测试我的代码时,它给了我bad_alloc异常并崩溃。我尝试使用较小的文件,并且适用于小于500Mo的文件,但是文件越大,随机崩溃的可能性就越大。
你能帮助我吗?
这是崩溃发生的代码。它是在请求的主体构建时:

std::ifstream ifile(file.second, std::ios::binary | std::ios::ate); //the file I am trying to send
std::streamsize size = ifile.tellg();
ifile.seekg(0, std::ios::beg);
char *buff = new char[size];
ifile.read(buff, size);
ifile.close();
std::string ret(buff, size); //this make the bad_alloc exception
delete[] buff;
return ret; //return the body of the file in a string
谢谢

最佳答案

std::string ret(buff, size);创建buff的副本。因此,您实际上将内存消耗增加了一倍
https://www.cplusplus.com/reference/string/string/string/

(5) from buffer

Copies the first n characters from the array of characters pointed by s.


然后问题就变成了您实际拥有多少,以及您的操作系统允许您获得多少(例如,Linux上的ulimit)
正如评论所说,您应该对读取进行分块,并发送具有多个POST请求的单个块。
您可以循环ifstream检查是否达到ifile.eof()作为循环的退出条件:
std::streamsize size = 10*1024*1024 // read max 10MB
while (!ifile.eof())
{
    std::streamsize readBytes = ifile.readsome(buff, size);
    // do your sending of buff here.
}
您需要考虑错误处理,并且不要泄漏buff或将ifile保持打开状态。

关于c++ - 创建4GB std::string时分配错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64982482/

相关文章:

c++ - bad_alloc 标识符无法识别?

c++ - 列表分配错误 <shared_ptr>

c++ - 为什么在尝试推送到 vector 时会出现 std::bad_alloc 错误?

c++ - vector.push() 和 vector.reserve() 上的 bad_alloc

c++ - Qsort()比较struct int之和

java - 扩大/缩小转换的实际应用?

c++ - 在 QML 中旋转图像时降低 CPU 使用率

c++ - STD Bad Alloc 异常

C++指针查询

c++ - 从派生类之一调用基方法