我寫了下面的C函數,它在必要的內存分配後返回一個雙指針。C內存分配和釋放
// integer double pointer to 2d array
void** idp_to_2d (int rows , int cols) {
int i ;
void **est = malloc (rows * sizeof (int*)) ;
for (i = 0 ; i <= rows ; i ++)
est[i] = malloc (cols * sizeof (int)) ;
return est ;
}
然後我收到使用下面的代碼this指針從main()
:
int **est = (int**) idp_to_2d (rows , cols) ;
它工作正常,我可以像est[i][j]
意味着內存索引被正確分配。
現在我釋放內存中main()
使用下面的代碼:
int i ;
for (i = 0 ; i <= rows ; i ++)
free (est[i]) ;
free (est) ;
現在,我得到雙重釋放或腐敗錯誤。
我的編譯器GCC 4.9.2,OS是的Ubuntu 15.04(64位),我使用NetBeans IDE的8.0.2。
用[*未定義行爲*](http://en.wikipedia.org/wiki/Undefined_behavior)的問題是,它可能會* *似乎工作沒關係,和你有不確定的行爲,當你走超出分配內存的界限。 –