Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: "pointer being freed was not allocated" in c

this error is always fired, when i'm try to free my allocated struct the second time, which it shouldn't, because the struct is set to NULL after i'm freeing it.

here's my struct with no real pointer inside it:

 typedef struct{
        int frame; 
        double timestamp; 
        int identifier; 
        int state; 
        int unknown1; 
        int unknown2; 
        mtVector normalized;
        float size; 
        int unknown3;
        float angle; 
        float majorAxis;
        float minorAxis;
        mtVector unknown4; 
        int unknown5[2]; 
        float unknown6; 
    }Touch;

the barebone main function:

int main(){
    Touch *myTouch = NULL;
    int inputCounter = 0;
    //whenever  a touch is recognized:
    ...
    myTouch = (Touch*)realloc(myTouch,sizeof(Touch)*(inputCounter++));
    ...
    // everything works fine until:
    freeTouch(myTouch);
}

void freeTouch(Touch *f){
    if(f != NULL){
        free(f);
        f = NULL;
    }
}

anybody got an idea?

like image 986
Peter Piper Avatar asked Apr 02 '12 10:04

Peter Piper


1 Answers

f is a local variable. free(f) will affect the allocated memory, but f = NULL has no impact on myTouch in freeTouch(myTouch);.

Try

void freeTouch(Touch **f){
    if(*f != NULL){
        free(*f);
        *f = NULL;
    }
}

instead and use freeTouch(&myTouch).

like image 195
Zeta Avatar answered Nov 15 '22 07:11

Zeta