[英]about limit of the array output to file in c++
我用c ++編寫了一段代碼來測試64位(redhat linux)系統中文件輸出的限制。 硬盤和內存非常大(1TB和64Gb)。 我認為由於64位地址,輸出文件的最大大小為2 ^ 63字節。 我使用sizeof來驗證c ++(g ++編譯器)中的以下數據類型
sizeof(double) = 8, sizeof(size_t) = 8, sizeof(std::streamsize) = 8
以下代碼效果很好
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
char data[200000][10000];
fstream outfile("output.dat", ios::out | ios::binary);
outfile.write(&data[0][0], 200000*10000);
outfile.close();
return 0;
}
但如果我用雙倍代替
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
double data[200000][10000];
fstream outfile("output.dat", ios::out | ios::binary);
outfile.write((char*)&data[0][0], sizeof(double)*200000*10000);
outfile.close();
return 0;
}
觀察到“分段錯誤(核心傾倒)”。 但是我不明白為什么因為sizeof(double)* 200000 * 10000 <2 ^ 63,所以應該可以輸出那個大小的數組。
您的陣列太大而無法放入堆棧,無論您擁有多少RAM,其數量都有限。 快速解決方法是讓它們保持靜態。 更好的解決方案是使用new或vector動態分配它們。 你的數組是2d的事實使得傳遞指向文件的指針有點棘手。 你能做這個嗎?
vector<double> data(2000000000);
fstream outfile("output.dat", ios::out | ios::binary);
outfile.write((char*)&data[0], data.size() * sizeof (double));
如果這會拋出std::bad_alloc
那么你的操作系統沒有足夠的內存來提供。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.