2016-10-11 60 views
1

我發現這個錯誤有很多線程,但一直無法找到適合我的解決方案。我試圖從PGM圖像讀取數據並將其放入矩陣中。我的問題是內存重新分配失敗,出現錯誤realloc: invalid old size。下面是代碼的摘錄,顯示了重新分配的方式。realloc:無效的舊尺寸

typedef struct num_matrix { 
    int ** data; 
    int rows; 
    int cols; 
} matrix; 

[in loadPGMImageFromFilename] 
matrix m; 
m.data = (int**)malloc(0*sizeof(int)); 
loadPGMImageData(m); 

[in void loadPGMImageData(matrix &m)] 
ss >> m.rows >> m.cols; // <- sets rows and cols, seems to work 
allocateMatrixMemory(m); 

void allocateMatrixMemory(matrix &m) { 
    int** temp = (int**) realloc(m.data, m.rows*sizeof(int)); // <- ERROR 
    //more stuff 
} 
+4

'(int **)malloc(0 * sizeof(int));'?這是故意的嗎? –

+1

是[tag:c] ?? ... – LPs

+1

'ss >> m.rows >> m.cols;'那該做什麼或做什麼? –

回答

-4

出於這種行後我的頭, 的頂部的 - > m.data =(INT **)的malloc(0 *的sizeof(int)的); m.data爲空。 您不能重新分配空值。

+0

這是一條評論,而不是答案。 –

+0

,這可能是一個有效的指針:'如果大小爲0,則malloc()返回NULL或者稍後可以成功傳遞給free()的唯一指針值。 ' –

+4

帶'NULL'指針的'realloc'作爲第一個參數與'malloc'調用相同。 – mch