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 ***
我在做什麼錯了?謝謝。
在'cellCopyValues()'中,完成'* targetcell = * sourcecell'就足夠了。 – Philip 2011-04-14 08:07:46