【问题标题】:Deallocate contiguous block of memory for a 2D array为二维数组释放连续的内存块
【发布时间】:2022-01-06 08:24:33
【问题描述】:
我知道我将数组拆分为双指针,但是如果我丢失了数据轨道,我该如何解除分配?
#include <stdio.h>
#include <stdlib.h>
#define width 20
#define height 20
void allocate_matrix(int ***matrix)
{
double **local_matrix, *data;
local_matrix = (double **)malloc(sizeof(double *) * height);
data = (double *)malloc(sizeof(double) * width * height);
for (int i = 0; i < height; i++)
{
local_matrix[i] = &(data[i * width]);
}
*matrix = local_matrix;
}
void deallocate_matrix(int **matrix) {
}
int main(void) {
int **matrix;
allocate_matrix(&matrix);
deallocate_matrix(matrix);
return 0;
}
【问题讨论】:
标签:
c
memory
dynamic
free
【解决方案1】:
您没有忘记第二个指针。如果您查看循环体:
local_matrix[i] = &(data[i * width]);
i 为 0 时,local_matrix[0] 赋值为 &data[0],与 data 相同。这就是你需要释放的东西:
void deallocate_matrix(int **matrix) {
free(matrix[0]);
free(matrix);
}
【解决方案2】:
首先,您为double 分配空间,然后将其用作int,这没有意义(并且不会编译)。
但这里的主要问题是您不应该将其分配为碎片段,而应分配为连续的 2D 数组。请学习Correctly allocating multi-dimensional arrays。这将大大提升性能,并且可能(可以说)使代码更易于阅读。
如果我们遵循该帖子中的建议,那么您的代码可以重写为:
#include <stdio.h>
#include <stdlib.h>
void allocate_matrix(size_t height, size_t width, int (**matrix)[height][width])
{
int (*local_matrix) [height][width];
local_matrix = malloc(sizeof *local_matrix);
if(local_matrix == NULL)
{
// handle errors
}
*matrix = local_matrix;
}
int main (void)
{
const size_t height = 20;
const size_t width = 20;
int (*matrix)[height][width];
allocate_matrix(height, width, &matrix);
int(*pmatrix)[width] = *matrix; // pointer to first 1D array for easier syntax
for(size_t h=0; h<height; h++)
{
for(size_t w=0; w<width; w++)
{
pmatrix[h][w] = h+w; // assign some sort of data
printf("%d ", pmatrix[h][w]);
}
printf("\n");
}
free(matrix);
return 0;
}
如您所见,这也消除了对复杂释放例程的需要,因为我们可以直接将指针传递给 free() 并在一个地方释放所有内容。
【解决方案3】:
以下建议的代码:
- 需要头文件:
stdlib.h 用于 exit() 和 malloc() 以及 EXIT_FAILURE 的原型
- 执行所需的功能
- 您可能想要修改矩阵初始化值的计算
现在,建议的代码:
double **allocate_matrix(void)
{
local_matrix** = malloc( sizeof(double *) * height );
if( ! local_matrix )
{
perror( "malloc for matrix height failed:");
exit( EXIT_FAILURE );
}
for( size_t y = 0; y<height; y++ )
{
local_matrix[y] = malloc( sizeof(double) * width );
if( !local_matrix[y] )
{
//cleanup and exit
}
for ( size_t i = 0; i < width; i++)
{
local_matrix[y][i] = i;
}
}
return local_matrix;
}
int main( void )
{
double **matrix;
matrix = allocate_matrix();
for( size_t y= 0; y< height; y++ )
{
free( matrix[ y ] ):
}
free( matrix );
}