我在尝试释放动态数组的内存时遇到错误。
void Ex()
{
int **Matrix = dyn_matrix_allocation(rows, cols);
.
.
.
free_My_Dyn_Mem(Matrix, rows);
}
void free_My_Dyn_Mem(int **to_Release, int size)
{
int i;
for (i = 0; i < size; i++)
free(to_Release[i]);
//free(to_Release); - If I do this, the program crash.
}
void **dyn_matrix_allocation(int rows, int cols)
{
void **matrix = (void**)calloc (sizeof(int*), cols);
assert(matrix); /*calloc worked*/
int i;
for (i = 0; i < rows; i++)
{
matrix[i] = (int*)calloc(sizeof(int), rows);
assert(matrix[i]); /*calloc worked*/
}
return matrix;
}
释放数组本身后,我尝试释放指针的指针(**matrix)
,然后出现错误。调试器没有显示任何特别的内容。有什么想法吗?
最佳答案
由于 2D 寻址的定义不明确,您在分配动态矩阵时犯了一些错误。
分配中的第一个错误,在这里您选择创建依赖于列的矩阵,分配 cols
指针数组 ti int
:
void **matrix = (void**)calloc (sizeof(int*), cols);
现在您应该为每列分配一个rows
整数数组,但您分配rows
整数数组:
for (i = 0; i < rows; i++) //Should be for (i = 0; i < cols; i++)
{
matrix[i] = (int*)calloc(sizeof(int), rows);
assert(matrix[i]); /*calloc worked*/
}
到目前为止,一些编译器、lint 甚至优秀的调试器应该已经告诉您,您的位置超出了界限。
但是当您仍然使用错误的寻址释放内存时,会触发异常。
void Ex()
{
int **Matrix = dyn_matrix_allocation(rows, cols);
.
.
.
free_My_Dyn_Mem(Matrix, rows); //But you allocated cols pointers...
}
您应该传递大小为 cols
成员的整数指针数组,而不是 rows
。
现在您释放超出范围的分配内容:
for (i = 0; i < size; i++)
free(to_Release[i]);
调试器应该提示很多!
然后你释放一个现已损坏的内存...
free(to_Release);
您的代码应该是:
#include <stdlib.h>
#include <assert.h>
void free_My_Dyn_Mem(int **to_Release, int size)
{
int i;
for (i = 0; i < size; i++)
free(to_Release[i]);
free(to_Release); //- If I do this, the program crash.
}
int **dyn_matrix_allocation(int rows, int cols)
{
int **matrix = calloc(sizeof(int *), cols);
assert(matrix); /*calloc worked */
int i;
//for (i = 0; i < rows; i++)
for (i = 0; i < cols; i++)
{
matrix[i] = calloc(sizeof(int), rows);
assert(matrix[i]); /*calloc worked */
}
return matrix;
}
void Ex(void)
{
int rows = 100;
int cols = 20;
int **Matrix = dyn_matrix_allocation(rows, cols);
//.
//.
//.
//free_My_Dyn_Mem(Matrix, rows);
free_My_Dyn_Mem(Matrix, cols);
}
请记住您选择了按列排序的矩阵。
附注我忘记补充一点,断言通常用于开发检查,并且可以通过定义符号 NDEBUG 来删除它们。当您需要永久控制时,例如分配返回错误,您应该使用标准 if (condition) ErrorHandling(...);
。
关于c - 释放C中指针的指针的动态内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49830504/