我正在尝试在C中创建一个高斯滤波器内核,以进行一些图像处理。我在堆上使用2d浮点数组,但是当我在行上调用free()时,我不断得到free():无效的指针错误。我已经将内存位置和过滤器的值打印出到标准输出,一切似乎都与我期望的一样
Comparator.nullsFirst
这是我要输出到标准输出的输出
//kernel->kernel = float **
//kernel->row_len = kernel->col_len = 5
float total_weight = 0.0;
//build the holding col
kernel->kernel = malloc(sizeof(float *) * kernel->col_len);
//get mem for each row and set the values
for (int j = 0; j < kernel->col_len; j++)
{
kernel->kernel[j] = malloc(sizeof(float) * kernel->row_len);
for (int i = 0; i < kernel->row_len; i++)
{
kernel->kernel[j][i] = ken_ComputeGuassianVal(i, j, sigma, size);
total_weight += kernel->kernel[j][i];
}
//print debugging info
printf("Create - %p\n", (kernel->kernel + j));
for (int i = 0; i < kernel->row_len; i++)
{
printf("%d, %d - %f \n", i, j, kernel->kernel[j][i]);
printf("%p\n", (*(kernel->kernel + j) + i));
}
printf("\n");
}
//Normalise the kernel otherwise brightness will be added to the image
for (int j = 0; j < kernel->col_len; j++)
{
for (int i = 0; i < kernel->row_len; i++)
{
kernel->kernel[j][i] /= total_weight;
}
}
for (int j = 0; j < kernel->col_len; j++)
{
printf("Attempting to free memory at location %p\n", (kernel->kernel + j));
free(kernel->kernel + j);
printf("\n");
}
free(kernel->kernel);
我尝试了两种数组符号kernel-> kernel [j]和(kernel-> kernel + j)。我正在使用基本的Linux 5.0和GCC版本7.3.0(Ubuntu 7.3.0-27ubuntu1〜18.04)
编辑:在标准化循环中将停止条件变量更改为使用与其他循环相同的变量。在末尾为双指针添加了免费声明
答案 0 :(得分:0)
规则是:每个free()
应该有一个对应的malloc()
struct matrix {
unsigned nrow;
unsigned ncol;
float ** ptrs;
} data;
/* allocate */
unsigned row, col;
data.ptrs = malloc (data.nrow * sizeof *data.ptrs); // <<< [A]
for (row=0; row < data.nrow; row++) { // <<< [B]
data.ptrs[row] = malloc (data.ncol * sizeof *data.ptrs[0]); // <<< [C]
}
/* there should be a corresponding free for every malloc
, but in the "inside-out" order :
*/
unsigned row, col;
for (row=0; row < data.nrow; row++) { // <<< [B]
free( data.ptrs[row] ); // <<< [C]
}
free(data.ptrs); // <<< [A]
注意:为简单起见,我交换了行/列,并使用matrix.field
代替了pointer->field
。