[英]Problems when freeing a dynamically allocated 2d array in C
我拼命試圖釋放一個 2d int 數組,但無法做到。 我猜我初始化數組時出了什么問題? 你能幫幫我嗎?
int rows = 2;
int cols = 3;
int *mfields = (int *) malloc(sizeof(int) * rows * cols);
int **matrix = (int **) malloc(sizeof(int *) * rows);
for (int i = 0; i < rows; i++) {
matrix[i] = mfields + i * cols;
for(int j=0; j<rows;j++) {
matrix[i][j] = (i+1)*(j+1);
}
}
for (int i = 0; i < rows; i++) {
free((matrix[i]));
}
free(matrix);
提前致謝,克里斯蒂安
分配了 memory 的兩個塊:
int *mfields = (int *) malloc(sizeof(int) * rows * cols);
int **matrix = (int **) malloc(sizeof(int *) * rows);
因此應該釋放 memory 的兩個塊:
free(matrix);
free(mfields);
像這個循環一樣釋放 memory 的多個塊:
for (int i = 0; i < rows; i++) {
free((matrix[i]));
是不正確的,因為它將從未從malloc
返回的地址傳遞給free
。
通常,將矩陣實現為指向指針的指針是不好的。 這會阻止處理器進行負載預測並降低性能。 如果將與代碼一起使用的 C 實現支持可變長度 arrays,那么最好只分配一個 memory 塊:
int (*matrix)[cols] = malloc(rows * sizeof *matrix);
如果可變長度數組支持不可用,則程序應分配一塊 memory 並使用手動計算來尋址數組元素。 雖然這對程序員來說可能需要更多的工作,但它對性能更好:
int *matrix = malloc(rows * cols * sizeof *matrix);
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i*cols + j] = (i+1) * (j+1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.