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

时间:2011-04-14 05:13:49

标签: 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 *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 ***

我做错了什么?感谢。

1 个答案:

答案 0 :(得分:5)

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

您的cn被分配为8 struct cell的数组,但实际上您正在尝试释放&cn[0], &cn[1], &cn[2],这些cn实际上并未使用malloc分配,而malloc需要它自己免费。

你应该只释放malloc得到的那些指针,并记住一条好的规则,即释放的数量必须与malloc的数量相对应。

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

如果计算malloc,则为16,但是{{1}}是免费的。

相关问题