双重释放或损坏 - 为C中的矩阵释放内存

时间:2016-10-15 09:04:49

标签: c matrix memory-management memory-leaks

我有这个程序用拉普拉斯方法计算矩阵的行列式。它工作正常,但是当我尝试在deleteMatrix()函数内部使用det()时,它会释放内存。 Matrix是从文本文件加载的,但我很确定它没问题,所以我正在跳过这部分代码。

我收到错误:*** Error in ./prog: double free or corruption (out): 0x00000000008a0910 *** 我想我可能会在某个地方超越阵列,但我找不到它。 我的目标是不在此代码中造成任何内存泄漏。

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

//...
// text file reading and matrix creating functions
//...

void deleteMatrix(double** matrix, int n){

    int i,j;
    for(i = 0; i < n; i++){
        free(matrix[i]);
    }
    free(matrix);
}

double** createMinor(double** matrix, int n, int banned){

    double** minor = (double**)calloc(n-1, sizeof(double*));
    int i,j;
    int i2 = 0, j2 = 0;

    for(i=0; i<n; i++){
        minor[i] = (double*)calloc(n-1, sizeof(double));

        for(j=0; j<n; j++){

            if(i != 0 && j != banned){

                if(j2<n-1){
                    minor[i2][j2] = matrix[i][j];
                    j2++;

                }else{
                    i2++;
                    minor[i2][0] = matrix[i][j];
                    j2 = 1;
                }
            }
        }
    }
    return minor;   
}

double det(double** matrix, int n){

    double sum = 0.0;
    double sign = 1.0;
    int i;

    double** minor = (double**)calloc(n - 1, sizeof(double*));

    if(n==1)
        return matrix[0][0];
    if(n==2)
        return matrix[0][0]*matrix[1][1]-matrix[0][1]*matrix[1][0];

    for(i=0; i<n; i++){
        //creating submatrix

        minor = createMinor(matrix, n, i);
        //-----------

        sum+= sign*matrix[0][i]*det(minor,n-1);
        sign = -sign;

    };

    deleteMatrix(matrix, n);   // <---- line causing error

    return sum;
}

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

    //-------------------------------
    //Reading matrix from a text file

    const char* filename = "file.txt";

    FILE *fp = fopen(filename, "r");
    if(fp == NULL){
        puts("Error - opening file");   
        exit(1);
    }

    double size = findSize(fp);
    double** matrix = createMatrix(fp, size);
    //-------------------------------

    double deter = det(matrix, size);

    printf("Determinant: %f\n", deter);

    deleteMatrix(matrix, size);
    fclose(fp);
    return 0;
}

0 个答案:

没有答案