memory - c free() works when I call but not in my function -


i learning c , playing malloc , free. reason when use free() in main works when put in function not

  #include <stdlib.h>   #include <stdio.h>    struct st {     int number;   };   void del(struct st *s) {     if (s == null) return;     free(s); s = null;   }   int main() {     struct st *s;     s = (struct st *)malloc(sizeof(struct st));     s->number = 4;     printf("the value is: %d", s->number);     del(s);   //  free(s); s= null;     if(s == null) printf("\nthe struct removed memory\n");     else printf("\nthe value is: %d\n", s->number);     return 0;   } 

this echo:

the value is: 4 value is: 0 

but if do:

   // del(s);     free(s); s= null; 

it works

you passing pointer function, means has access local copy of pointer. free(s) free local copy. if want free variable, outside of scope of function call free, need gain access derefering again (passing pointer pointer).

void del(struct st **s) {     if (*s == null) return;     free(*s);      *s = null; } 

should work fine.

edit: call function del(&s);


Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -