如何正确释放某些malloc';d数组元素?

如何正确释放某些malloc';d数组元素?,c,arrays,struct,malloc,free,C,Arrays,Struct,Malloc,Free,我正在使用以下结构和方法: struct cell { double x, y, h, g, rhs; struct key *keys; }; void cellFree(struct cell *c) { free(c->keys); c->keys = NULL; free(c); c = NULL; } void cellCopyValues(struct cell *targetcell, struct cell *s

我正在使用以下结构和方法:

struct cell {
    double x, y, h, g, rhs;
    struct key *keys;
};

void cellFree(struct cell *c)   {
    free(c->keys);
    c->keys = NULL;
    free(c);
    c = NULL;
}

void cellCopyValues(struct cell *targetcell, struct cell *sourcecell)   {
    targetcell->x = sourcecell->x;  
    targetcell->y = sourcecell->y;  
    targetcell->h = sourcecell->h;  
    targetcell->g = sourcecell->g;  
    targetcell->rhs = sourcecell->rhs;  
    keyCopyValues(targetcell->keys, sourcecell->keys);
}

struct cell * cellGetNeighbors(struct cell *c, struct cell *sstart, struct cell *sgoal, double km)  {
    int i;

    // CREATE 8 CELLS
    struct cell *cn = malloc(8 * sizeof (struct cell));

    for(i = 0; i < 8; i++)  {
        cn[i].keys = malloc(sizeof(struct key));
        cellCopyValues(&cn[i], c);
    }


    return cn;
}

struct cell * cellMinNeighbor(struct cell *c, struct cell *sstart, struct cell *sgoal, double km)   {
    // GET NEIGHBORS of c
    int i;
    struct cell *cn = cellGetNeighbors(c, sstart, sgoal, km);
    double sum[8];
    double minsum;
    int mincell;

    cellPrintData(&cn[2]);

    // *** CHOOSE A CELL TO RETURN
    mincell = 3; // (say)


    // Free memory
    for(i = 0; i < 8; i++)  {
        if(i != mincell)    {
            cellFree(&cn[i]);
        }
    }

    return (&cn[mincell]);
}

我做错了什么?谢谢。

您正在分配一个数组,然后尝试释放特定成员

您的
cn
被分配为一个由8个
struct cell
组成的数组,但实际上您正在尝试释放
&cn[0]、&cn[1]、&cn[2]
,而实际上并没有使用malloc进行分配,而malloc需要它自己的空闲空间

您应该只释放malloc得到的那些指针,需要记住的一个好规则是,释放的数量必须与malloc的数量相对应

在本例中,您可以使用malloc
cn
和各个键,但不能使用
&cn[1]
等。因此释放它们是一个错误

如果您计算malloc,则有
9
,但在
cellCopyValues()
中有
16

,这样做就完全足够了
*targetcell=*sourcecell
*** glibc detected *** ./algo: free(): invalid pointer: 0x0000000001cb81c0 ***