2016-11-04 84 views
0

我試圖讀取一個非常大的.txt文件,其中包含128x128x128 = 2097152行(線性化的3d空間),只包含一個0或1個行(不要問爲什麼)......我將代碼修剪成幾行,似乎當我關閉線和增量時,一切都很順利...但是,只要我想將數據放入一個足夠允許的數組中,行讀停在我= 12286 ...在C++中讀取一個大的.txt文件時奇怪的錯誤

這裏的代碼

int dim = nbvox[0]*nbvox[1]*nbvox[2]; 
float* hu_geometry = new float(dim); 
int* hu_temp = new int(dim); 
string line; 

int i = 0; 


ifstream in(hu_geom_file.c_str()); 
if(in.is_open()) 
{ 
    while(getline(in, line)) 
    { 

    hu_temp[i] = stoi(line); 
    cout << "i= " << i << " line= " << line << " hu_temp= " << hu_temp[i] << endl; 
    i++; 
    } 
    cout << __LINE__ << " i=" << i << endl; 
    in.close(); 
    cout << __LINE__ << endl; 
} 
else cout << "Unable to open " << hu_geom_file << endl; 

這裏是最後的輸出得到的錯誤之前,我......這是因爲每當我的評論裏t時的hu_temp線很奇怪他一會兒,COUT獨自工作到2097152.

i= 12276 line= 0 hu_temp= 0 
i= 12277 line= 0 hu_temp= 0 
i= 12278 line= 0 hu_temp= 0 
i= 12279 line= 0 hu_temp= 0 
i= 12280 line= 0 hu_temp= 0 
i= 12281 line= 0 hu_temp= 0 
i= 12282 line= 0 hu_temp= 0 
i= 12283 line= 0 hu_temp= 0 
i= 12284 line= 0 hu_temp= 0 
i= 12285 line= 0 hu_temp= 0 
115 i=12286 
*** Error in `G4Sandbox': free(): invalid pointer: 0x0000000001ba4c40 *** 
Aborted (core dumped) 

回答

6
float* hu_geometry = new float(dim); 
int* hu_temp = new int(dim); 

那些包含值dim 1 - 字符數組。在某個時候,你正在碰到一個MMU邊界並隨機崩潰。

你想寫:

float* hu_geometry = new float[dim]; 
int* hu_temp = new int[dim]; 

或可能與載體較好,預分配與dim元素

#include <vector> 
std::vector<float> hu_geometry(dim); 
std::vector<int> hu_temp(dim); 

或者根本不開始分配:

std::vector<int> hu_temp; 

,並在您的代碼:

hu_temp.push_back(stoi(line)); 

hu_temp.size()給出的大小和很多更好地描述here非常不錯的功能)

+0

我覺得自己很蠢,現在笑......但多謝......這是由3人審查,併爲工作很多時間纔將它發佈到堆棧上...我想我們需要從我們的代碼中獲得一些空間... – Feynstein

+0

此問題始終在發生。需要一個很好的眼睛來抓住它。根本不使用數組,而是使用矢量來修正它。 –

+0

是的,但我發現它們很難在我的代碼中稍後處理,因爲這都與CUDA混合在一起......我通常會使用矢量,但之後我必須在將它們發送給GPU之前與它們一起工作 – Feynstein