【问题标题】:Can't spot double free无法发现双重免费
【发布时间】:2021-09-16 09:32:42
【问题描述】:

我尝试使用动态内存分配来初始化一个矩阵,为此我创建了一个辅助函数。 当我尝试释放内存时出现问题。我收到双重释放或损坏错误。

我了解什么是双重释放错误,但无法在我的代码中发现它。

void
delete_matrix(matrix_t *mat)
{
    for(int i = 0; i < mat->rows; i++)
    {
        free(mat->data[i]); /* It crashes at first iteration */
        mat->data[i] = NULL;
    }
    free(mat->data);
    mat->data = NULL;
}


int
init_matrix(matrix_t *mat, int rows, int cols)
{
    mat->rows = rows;
    mat->cols = cols;

    mat->data = (int**)malloc(rows * sizeof(int));

    for(int i = 0; i < rows; i++)
    {
        mat->data[i] = (int*)malloc(cols * sizeof(int));
    }
    return 0;
}

gdbonline.com上的完整代码:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

typedef struct
{
    int ** data;
    int rows;
    int cols;
}matrix_t;

int  init_matrix(matrix_t *mat, int rows, int cols);
void delete_matrix(matrix_t *mat);

int
main()
{
    printf("> Program started\n");

    matrix_t mat_A;
    init_matrix(&mat_A, 1000, 1000);
    delete_matrix(&mat_A);
    printf("> Program done\n");
    sleep(0);
    return 0;
}


int
init_matrix(matrix_t *mat, int rows, int cols)
{
    mat->rows = rows;
    mat->cols = cols;

    mat->data = (int**)malloc(rows * sizeof(int));
    if(!mat->data)
    {
        printf("! malloc error (init_matrix 1)\n");
        return -1;
    }

    for(int i = 0; i < rows; i++)
    {
        mat->data[i] = (int*)malloc(cols * sizeof(int));
        if(!mat->data[i])
        {
            printf("! malloc error (init_matrix 2)\n");
            return -1;
        }
    }
    return 0;
}


void
delete_matrix(matrix_t *mat)
{
    for(int i = 0; i < mat->rows; i++)
    {
        free(mat->data[i]);
        mat->data[i] = NULL;
    }
    free(mat->data);
    mat->data = NULL;
}

提前谢谢你。

【问题讨论】:

  • rows * sizeof(int)?我猜你真的想要rows * sizeof(int*)。或者更好的是 rows * sizeof *mat-&gt;data 如果 sizeof(int) &lt; sizeof(int*) 为真(通常在 64 位系统上),那么您将分配给很少的内存并超出范围并具有 未定义的行为 (等等像你得到的错误)。
  • 顺便说一句,在 C 中你是 shouldn't really cast the result of malloc(或其他函数返回 void*)。
  • 是的,问题似乎出在分配上。

标签: c malloc free


【解决方案1】:

我收到双重免费或损坏错误。

不正确的分配可能导致损坏。

//                                         v-v---- wrong type. 
// mat->data = (int**)malloc(rows * sizeof(int));
mat->data = malloc(sizeof *(mat->data) * rows);
//                 ^-----------------^ The right size by construction
//                                     No need to code the matching type 

【讨论】:

    猜你喜欢
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    • 2016-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多