In my code, I have several pointers to pointers (e.g. float ** variables), and I seem to be having issues freeing up their memory so as to not cause memory leaks. Here is the code that I have written:
float *one, **part1, **part2;
one = malloc(sizeof(&one) * nx * nx);
part1 = malloc(sizeof(&part1) * nx);
if(one == NULL || part1 == NULL) {
printf("Memory error.\n");
exit(2);
}
for(k = 0; k < nx; k++)
part1[k] = &one[k * nx];
one = malloc(sizeof(&one) * nx * nx);
part2 = malloc(sizeof(&part2) * nx);
if(one == NULL || part2 == NULL) {
printf("Memory error.\n");
exit(2);
}
for(k = 0; k < nx; k++)
part2[k] = &one[k * nx];
... (Other code here)
for(k = 0; k < nx; k++) {
free(part1[k]);
free(part2[k]);
}
free(one);
free(part1);
free(part2);
This code runs through, does the calculations correctly, but then errors out in the free loop. It works for k = 0, but then when trying to free part1[1] and part2[1], it gives me the “glibc detected” error.
First of all:
These should be
You want to allocate a bunch of
floats andfloat *s, notfloat **s andfloat ***sSecondly, you make 4 allocations — you allocate
one, and indices into it inpart1,and allocate
oneagain, (forgetting the old address), and indices into it inpart2.This means you should have 4
free()s:part1,part2, and both chunks of memory to whichonepointed. Because you overwrite the firstone, you’ve lost that pointer and can’t directlyfree()it. Fortunately you did save that pointer inpart1[0], and can use that tofree()all the memory pointed to.Another (perhaps clearer and more idiomatic) option would be to allocate differently. Allocate
part1, and then loop to allocate eachpart1[k], and the same forpart2.