"Pointer being freed was not allocated." error after malloc, realloc
c, dynamic-arrays, pointers
Solution
`realloc` may move the memory to a new location (if there is not enough space to expand the old pointer). If that happens, you need to free the new pointer.
Try this tweak:
int main(){
point *points = malloc(sizeof(point));
if (points == NULL){
printf("Memory allocation failed.\n");
return 1;
}
other_stuff(&points);
free(points);
return 0;
}
void other_stuff(point **points){
//stuff
point *temp = realloc(*points, number*sizeof(point));
if(temp != NULL) {
*points = temp;
// and do your stuff
}
else {
// panic? memory reallocation failed. Deal with it gracefully.
}
}
By passing a handle to `other_stuff`, we give it control not only over the place where the pointer is pointing, but to the address of the pointer itself. This allows it to move the memory around. Handles are a good way to manage memory dynamically; but conceptually a pointer to a pointer takes some getting used to...
Problem
I have this error with the following code: ``` int main(){ point *points = malloc(sizeof(point)); if (points == NULL){ printf("Memory allocation failed.\n"); return 1; } other_stuff(points); free(points); return 0; } void other_stuff(point points[]){ //stuff realloc(points, number*sizeof(point)) } ``` I have searched, but found only examples where it was clear there was no allocation. Here, I used `malloc` to initialise `points`, and later changed its size with `realloc`; so how is the pointer "not allocated" when I come to `free` it?