我試圖創建一個具有以下功能的代碼多維int數組:動態二維數組創建運行時錯誤
int ** createIntMatrix(unsigned int rows, unsigned int cols)
{
int ** matrix;
unsigned int i,j;
matrix = (int **) calloc(cols, sizeof(int *));
for(i = 0; i < cols; i++)
matrix[i] = (int *) calloc(rows, sizeof(int));
for(i = 0; i < cols; i++)
for(j = 0; j < rows; j++)
matrix[i][j] = 0;
return matrix;
}
創建下面的代碼使用此功能三個實例,
cout<<"allocating temporary data holders..."<<endl;
int ** temp_meanR;
int ** temp_meanG;
int ** temp_meanB;
temp_meanR = createIntMatrix(img->height,img->width);
temp_meanG = createIntMatrix(img->height,img->width);
temp_meanB = createIntMatrix(img->height,img->width);
cout<<"....done!"<<endl;
我正在訪問這些元素,例如temp_meanB[4][5]
。
但不幸的是,我得到運行時出現以下錯誤:
allocating temporary data holders...
....done!
tp6(1868) malloc: *** error for object 0x122852e08: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
Abort trap
我要去哪裏錯了嗎?
爲什麼你使用calloc而不是新的? – Gal 2011-05-18 13:17:02
如果使用'calloc'分配內存,則不需要手動將元素初始化爲零。根據http://www.cplusplus.com/reference/clibrary/cstdlib/calloc/所有位自動設置爲0。 – 2011-05-18 13:18:50
malloc是C的方式,在C++中使用新的。 – snoofkin 2011-05-18 13:23:04