1

I try to free structure pointer using function and then check for NULL. It doesn't work!

typedef struct{
    int * num;
} D;

void freeD(D * a){
    free(a->num);
    free(a);
    a=NULL;
}
int main(){
    D * smth = malloc(sizeof(D));
    smth->num = malloc(sizeof(int)*2);
    freeD(smth);
    if(smth==NULL){
    printf("It's NULL");
    }
}
mblos
  • 23
  • 6
  • You change the local copy of the pointer, passed as the parameter `a`. – DYZ Jan 15 '17 at 19:08
  • Beginner error `D *a` is a local variable of `freeD()` change his value inside the function don't change the value of `smth` in the main. – Stargateur Jan 15 '17 at 19:09
  • 1
    Possible duplicate: http://stackoverflow.com/questions/9459691/how-to-change-value-of-variable-passed-as-argument – DYZ Jan 15 '17 at 19:10
  • 1
    a=NULL; has no effect – alinsoar Jan 15 '17 at 19:10
  • comparable with `void foo(int n) { n = 1; }` pretty useless huh? – AndersK Jan 15 '17 at 19:37
  • 1
    @alinsoar `a=NULL;` has no effect is true yet is an oft used coding style to improve chances of error should `a` get inadvertently get use later without a new assignment. So, not a bad thing to do in general, yet a bit odd at the end of a function. – chux - Reinstate Monica Jan 15 '17 at 20:35

2 Answers2

3

You have to pass the pointer by reference that is by using pointer to the pointer.

For example

void freeD(D ** a){
    free( ( *a )->num);
    free(*a);
    *a=NULL;
}

//...

freeD( &smth );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

Here you have passed the parameter by value instead of passing the parameter by reference.

What have you done
Let us assume smth=0x0030;
where address(smth) = 0x0100 && value(smth) = 0x0030.
So when you do freeD(smth), you are actually passing value(smth) which is 0x0030. Meanwhile, in the function freeD():-
address(a) = 0x0200 && value(a) = 0x0030
So when you do set

a = NULL

you are actually setting the value(a) = NULL where address(a)=0x0200; instead of doing it at the address=0x0100;

What you should have done

void freeD(D ** a){
free((*a)->num);
free(*a);
*a=NULL; 
}

int main(){
//...    
freeD(&smth);
//...
}
vkrishna17
  • 906
  • 10
  • 17