如何释放同时动态分配了每个索引的动态分配的内存?

时间:2019-02-06 23:38:45

标签: c oop free

对于一个项目,我试图在C中实现一个矩阵“类”,但是该矩阵的“析构函数”引发了异常。我不确定100%为什么,尽管我认为这是由于将变量重新分配给两个不同的动态分配的指针,然后尝试释放后者两次。我不能为此使用C ++,但我认为我会尽力模拟该功能。

这是代码,我不包括需要预定义的任何函数或结构的声明:

struct vComplex {
    double* realp;
    double* imagp;
    uint32_t length ; // for bookkeeping
    BOOL(*isreal)(vComplex);
    void(*free)(vComplex*);
    void(*print)(vComplex*);
}; 

struct mComplex { // complex matrix type
    vComplex* columns; // each vComplex represents one column of the mComplex
    uint32_t nCols;
    uint32_t nRows;
    BOOL (*isreal)(mComplex);
    void (*free)(mComplex*);
    void(*print)(mComplex*);
};

vComplex* createVComplex(uint32_t len) {

    vComplex* x = (vComplex*)malloc(sizeof(vComplex));

    x->realp = (double*)malloc(len * sizeof(double));
    x->imagp = (double*)malloc(len * sizeof(double));
    x->length = len;
    x->isreal = &isreal_v;
    x->free = &vComplex_free;
    x->print = &vComplex_print;

    return x;
}

mComplex* createMComplex(uint32_t nRows, uint32_t nCols) {
    mComplex* x = malloc(sizeof(mComplex));
    vComplex* vp;
    x->columns = (vComplex*)malloc(nCols * sizeof(vComplex));
    for (uint32_t i = 0; i < nCols; i++) {
        vp = createVComplex(nRows);
        x->columns[i] = *vp;
    }
    x->nRows = nRows;
    x->nCols = nCols;
    x->isreal = &isreal_m;
    x->free = &mComplex_free;
    x->print = &mComplex_print;

    return x;
}


void vComplex_free(vComplex* x) {
    free(x->realp);
    free(x->imagp);
    free(x); // error occurs here (only when called from mComplex_free)

    return;
}

void mComplex_free(mComplex* x) {
    for (uint32_t i = x->nCols - 1; i >= 0; i--) {
        x->columns[i].free(&x->columns[i]);
    }
    free(x);

    return;
}

vComplex.free似乎工作正常,但是mComplex.free引发异常。我的意图是createVComplex创建并返回指向vComplex的指针,然后该指针由vComplex.free释放。 createMComplex将为nCols个数量的vComplex个“对象”分配内存,然后一次释放一个。然后将释放指向vComplex数组的指针,最后释放指向mComplex的指针。我认为正在发生的事情是,我第一次在vComplex.free内部调用mComplex.free是因为某种原因它无法释放vComplex指针。

0 个答案:

没有答案