2011-04-14 70 views
2

我使用下面的结构和方法:如何正确释放某些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 *** 

我在做什么错了?谢谢。

+0

在'cellCopyValues()'中,完成'* targetcell = * sourcecell'就足够了。 – Philip 2011-04-14 08:07:46

回答

5

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

cn被分配到是8 struct cell数组,但你实际上是试图释放&cn[0], &cn[1], &cn[2],还没有真正使用它需要它自己的自由一个malloc分配。

你应该只释放你通过malloc得到的指针,并且要记住的一条好规则是释放的数量必须对应malloc的数量。

在这种情况下,你malloc cn和个人密钥,但不是&cn[1]等。所以释放他们是一个错误。

如果您计算mallocs,您有9,但释放是16

相关问题