通过传递到另一个功能来释放Dyanamic阵列
假设我具有一个函数,其中我
void fun() {
//does some stuff
double *matrix[row];
for (i = 0; i < row; i++)
matrix[i] = (double *)malloc(col * sizeof(double));
//does some stuff
free_matrix(matrix);
从函数中动态分配一个2D数组以释放矩阵。
void free_matrix(double **matrix, int row)
{
for (int i = 0; i < row; i++)
{
free(matrix[i]);
}
free(matrix);
}
在另一个功能中,将这样的内存交易吗?
Suppose I have a function where I dynamically allocate a 2D array
void fun() {
//does some stuff
double *matrix[row];
for (i = 0; i < row; i++)
matrix[i] = (double *)malloc(col * sizeof(double));
//does some stuff
free_matrix(matrix);
From the function I call another function to free the matrix.
void free_matrix(double **matrix, int row)
{
for (int i = 0; i < row; i++)
{
free(matrix[i]);
}
free(matrix);
}
Is deallocating memory like this in another function possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
代码中有许多问题,有多个问题的声明以及如何调用
free_matrix
。让我们首先修复这些内容:此汇编,但是运行时:
您只需要释放实际分配的实际分配即可。
您的大多数
free_matrix
功能都很好。对于矩阵中的每一行,您可以释放动态分配的内存。 但指向这些行的阵列不是动态分配的 。试图释放它会导致问题。修复很简单。删除最后一个
免费
。或者,动态分配整个矩阵。您可以动态分配行指针数组,然后动态分配每行,或者动态分配
row * col * col
元素,然后进行数学以访问每个行/COL坐标。There are a number of issues with variable declarations and how you call
free_matrix
in your code. Let's fix those first:This compiles, but when run:
You only need to free what you've actually dynamically allocated.
Most of your
free_matrix
functions is fine. For each row in the matrix, you free the dynamically allocated memory. But the array of pointers to those rows is not dynamically allocated. Trying to free it causes problems.The fix is simple. Remove that last
free
.Alternatively, dynamically allocate your entire matrix. You can either dynamically allocate your array of row pointers, and then dynamically allocate each row, or dynamically allocate
row * col
elements and do math to access each row/col coordinate.