"Pointer being freed was not allocated." error after malloc, realloc

Viewed 5685

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?

3 Answers

Thank you for the solution : realloc (MAY) return a NEW pointer.

Further, I believe that the following may help:

int main(){
    point   *points = malloc(sizeof(point));
    if (points == NULL){
        printf("Memory allocation failed.\n");
        return 1;
    }
    other_stuff(&points); /* Send address of points */
    free(points);
    return 0;
}
void other_stuff(point (*ppoints)[]){
    //stuff
    realloc(*ppoints, number*sizeof(point))  /* If a new storage area is assigned by     realloc the original points location will be updated in main */

}

Related