我正在使用多重解析器发送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/