为什么这个向量会抛出一个错误的分配异常



为什么这个看似无辜的函数会为noUrls=300,000,000抛出一个错误的分配异常?

#include <string>
#include <vector>
#include <algorithm>
void generateUrls(int noUrls)
{
std::vector<std::string> urls;
urls.resize(noUrls); //this always works
std::size_t i = 0;
std::string url = "abcdefghijklmnop";

urls[i] = "https://www." + url + ".com/home/index";
i++;

while (std::next_permutation(url.begin(), url.end()) && (i < noUrls))
{
urls[i] = "https://www." + url + ".com/home/index"; //this where it throws
i++;
}
}
int main()
{
generateUrls(100000000);
//do something with the result
return 0;
}

为什么?

线索:

  • noUrls=300,000,000没有导致溢出,我的平台的最大int大小为2147483647
  • 生成的矢量大约有12GB大
  • 我的系统有8GB的物理RAM,但页面文件的大小又是16GB,所以如果物理RAM用完,我本以为它只会在页面文件中粘贴一些矢量。(一个愚蠢的假设?(

您只计算字符,但std::string不仅仅是字符。在我的平台上,sizeof(std::string)是32。在开始添加任何字符之前,对于一个零长度字符串数组,这大约是9GiB。

如果字符串很短,大多数实现都会将字符保留在这32个字节内,以避免分配。但是你的字符串比这个长,所以字符是在免费存储中分配的。再加上12个GiB的字符,你就完全没有记忆了。

相关内容

最新更新