How do I properly free certain malloc'd array elements?
I'm using the following struct and methods:
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]);
}
When I call cellMinNeighbor()
I need to return one of the 8 spawned neighbors (from cellGetNeighbors()
) based on a selection criteria - however, the current method which I've applied to the free the other elements seems to be giving me the following error:
*** glibc detected *** ./algo: free(): invalid pointer: 0x0000000001cb81c0 ***
What am I doing wrong? Thanks.
You are allocating an array and then trying to free particular members.
Your cn
is allocated to be an array of 8 struct cell
, but you are actually trying to free &cn[0], &cn[1], &cn[2]
, which haven't actually been allocated using a malloc which requires it's own free.
You should free only those pointers you got by malloc and one good rule to remember is that the number of frees must correspond to the number of mallocs.
In this case, you malloc cn
and the individual keys, but not &cn[1]
etc. So freeing them is a mistake.
If you count the mallocs, you have 9
, but frees are 16
.
精彩评论