2013-03-02 20 views
0

所以我一直被困在內存問題上好幾天了。 我有一個使用C++運行的多線程程序。我初始化一個雙*指針。 從我讀過的和以前的編程經驗中,指針被初始化爲垃圾。如果將它初始化爲0或者如果爲程序分配的內存太多,它將爲空。對我來說,我的指針初始化,沒有分配,給了我一個空指針。 我寫的解析器函數是假設返回一個指向解析信息數組的指針。當我調用函數時,由編譯器將C++指針初始化爲空

double* data; 
data = Parser.ReadCoordinates(&storageFilename[0]); 

現在返回的指向數組的指針應該設置爲data。然後我嘗試從數組中打印出一些東西。我收到內存損壞錯誤。我已經跑了GDB,它給了我一個內存破壞錯誤:

*** glibc detected *** /home/user/kinect/openni/Platform/Linux/Bin/x64-Debug/Sample-NiHandTracker: free(): corrupted unsorted chunks: 0x0000000001387f90 *** 
*** glibc detected *** /home/user/kinect/openni/Platform/Linux/Bin/x64-Debug/Sample-NiHandTracker: malloc(): memory corruption: 0x0000000001392670 *** 

有人能向我解釋是怎麼回事?我嘗試初始化指針作爲一個全球性,但也不起作用。我試圖分配內存,但仍然出現內存損壞錯誤。解析器起作用。我用一個簡單的程序對它進行了測試。所以我不明白爲什麼它在我的其他程序中不起作用。我究竟做錯了什麼?如果需要,我還可以提供更多信息。

解析器代碼

雙* csvParser :: ReadCoordinates(字符*文件名){

int x;    //counter 
int size=0;   // 
char* data; 
int i = 0;   //counter 

FILE *fp=fopen(filename, "r"); 


if (fp == NULL){ 
perror ("Error opening file"); 
} 

while ((x = fgetc(fp)) != EOF) { //Returns the character currently pointed by the internal file position indicator 
    size++;  //Number of characters in the csv file 
} 

rewind(fp);       //Sets the position indicator to the beginning of the file 
printf("size is %d.\n", size);  //print 

data = new char[23];    //Each line is 23 bytes (characters) long 
size = (size/23) * 2;    //number of x, y coordinates 


coord = new double[size];   //allocate memory for an array of coordinates, need to be freed somewhere 

num_coord = size;     //num_coord is public 

//fgets (data, size, fp); 
//printf("data is %c.\n", *data); 

for(x=0; x<size; x++){ 
    fgets (data, size, fp); 
    coord[i] = atof(&data[0]);   //convert string to double 
    coord[i+1] = atof(&data[11]);  //convert string to double 
    i = i+2; 
} 


delete[] data; 

fclose (fp); 

return coord; 

}當你寫外面結合的陣列或向量的發生

+0

請發表更多的代碼。例如。 Parser.ReadCoordinates做什麼來分配內存...... – 2013-03-02 21:42:26

+0

要麼在'valgrind'下運行你的程序,要麼發佈足夠的代碼讓我們複製這個問題。 – 2013-03-02 21:42:40

+0

哇謝謝大家如此快速的迴應。我明白是什麼原因導致內存錯誤。但是,我不知道爲什麼我會收到錯誤。我已經添加了解析器代碼。但是,我不認爲我可以附加所有的代碼,因爲文件太多。 – user2127579 2013-03-02 23:57:45

回答

0

損壞存儲器。
它被稱爲heap underrun and overrun(取決於它在哪一側)。

堆的分配數據被破壞,所以您看到的症狀是free()或new()調用中的異常。
您通常不會獲得訪問衝突,因爲內存已分配並且屬於您,但是它被堆的邏輯使用。

找到你可能在數組邊界之外書寫的地方。