c语言 - 如何正确释放某些 malloc'd 数组元素?



我使用以下结构体和方法:

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]);
}

当我调用cellMinNeighbor()时,我需要根据选择标准返回8个派生邻居(来自cellGetNeighbors())中的一个-然而,我应用于释放其他元素的当前方法似乎给了我以下错误:

*** glibc detected *** ./algo: free(): invalid pointer: 0x0000000001cb81c0 ***

我做错了什么?谢谢。

你正在分配一个数组,然后试图释放特定的成员。

您的cn被分配为8个struct cell的数组,但您实际上试图释放&cn[0], &cn[1], &cn[2],它实际上没有使用malloc分配,这需要它自己的free。

你应该只释放那些通过malloc获得的指针,一个好的规则是释放的数量必须与malloc的数量相对应。

在这种情况下,您malloc cn和单个键,但不malloc &cn[1]等。所以释放它们是错误的。

如果你计算malloc,你有9,但自由是16

最新更新