【问题标题】:double free() error after swapping rows of a matrix交换矩阵行后出现双 free() 错误
【发布时间】:2013-01-17 04:21:55
【问题描述】:

我在执行代码时遇到双重释放或损坏错误。本质上,我只是在 C 中创建一个矩阵(任何 RxC 维度,这就是使用指针的原因),交换两行,打印结果,然后尝试释放内存。当我不交换行时,释放工作完美。当我这样做时,它会崩溃。我试图改变交换的方式无济于事。我认为这与交换超出范围的临时指针有关,但我不确定这是否是问题以及我将如何解决它。

MatElement 只是一个 double。

typedef double MatElement;

主要:

int main(int argc, char *argv[]) {

    MatElement** matrix = matrixAlloc(3,3);

    int i;
    int j;

    for(i = 0; i < 3; i++) {
        for(j = 0; j < 3; j++) {
            matrix[i][j] = i+j;
        }
    }
    matrixPrint(matrix, "%5.1f", 3, 3);
    swapRows(matrix, 0, 2);
    matrixPrint(matrix, "%5.1f", 3, 3);

    matrixFree(matrix);
    return 0;
}

矩阵的分配方式:

MatElement **matrixAlloc(int nr, int nc) {
    int i;
    MatElement *ptr;
    MatElement **A;

    A = malloc(nr * sizeof(MatElement *)); /* array of ptrs   */
    ptr = calloc(nr * nc, sizeof(MatElement)); /* matrix elements */
    for (i = 0; i < nr; i++) /* set row pointers properly */
        A[i] = ptr + nc * i;
    return A;
}

他们被释放的方式:

void matrixFree(MatElement **A) {
    free(A[0]);
    free(A);
}

它们的行交换方式:

void swapRows(MatElement** G, int pivotRow, int rowExamined) {
    MatElement* temp;

    temp = G[rowExamined];
    G[rowExamined] = G[pivotRow];
    G[pivotRow] = temp;
}

有没有人知道是什么导致了这种双重释放()/无效释放()?

【问题讨论】:

    标签: c memory memory-management memory-leaks matrix


    【解决方案1】:

    在某些时候,您将矩阵的第一行交换到另一个位置,因此 matrixFree() 中的 free(A[0]) 试图将指针释放到数组的中间,而不是 @987654323 返回的指针@。您需要将原始指针保存在某处,以便您可以将它不受干扰地传递给free()

    【讨论】:

    • 是的,解决了它。谢谢。
    【解决方案2】:

    你的矩阵看起来像这样:

    A 具有指向所有行的第一个元素的所有指针。所以最初,A[0] 指向第 0 行,A[1] 指向第 1 行,依此类推。

    因此,当您尝试释放矩阵时,您知道 A[0] 指向第一行。但是那时您假设您的矩阵元素处于连续位置,并且 A[0] 将始终指向 calloc 返回的初始指针。但是当你交换一些行(特别是第 0 行与任何其他行)时,A[0] 不会指向 calloc 返回的指针。

    可能的解决方案包括在 A 中再分配一个内存插槽:

    A = malloc( ((nr+1) * sizeof(MatElement )); / ptrs 数组 */

    然后将calloc返回的原始指针存储到A[nr]。

    所以,A[nr] 也会指向 calloc 返回的指针。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-29
      • 2019-03-24
      • 1970-01-01
      • 2017-02-17
      • 2013-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多