c - Why my free() wrapper function doesn't work? -
this question has answer here:
- c programming: malloc() inside function 8 answers
why should use pointer pointer in saferfree(void**) function when want free memory inside function? why below code does'n free ip pointer?
#include <stdio.h> #include <stdlib.h> #include <stdint.h> void saferfree(void *); int main() { int *ip; ip = (int*) malloc(sizeof(int)); *ip = 5; saferfree(ip); return 0; } void saferfree(void *pp){ if((void*)pp != null){ free(pp); pp = null; } }
above code doesn't free pp pointer below code double pointer works properly.i want know why?
#include <stdio.h> #include <stdlib.h> #include <stdint.h> void saferfree(void **); int main() { int *ip; ip = (int*) malloc(sizeof(int)); *ip = 5; saferfree(&ip); printf("%p", ip); return 0; } void saferfree(void **pp){ if(*pp != null){ free(*pp); *pp = null; } }
fwiw, safe pass null free()
. wrapper meaningless.
quoting c11
, chapter §7.22.3.3, (emphasis mine)
the
free
function causes space pointedptr
deallocated, is, made available further allocation. ifptr
null pointer, no action occurs. [..]
that said, per question, works fine, because accessing free-d memory ub, should not doing (which seem doing in main()
after calling saferfree()
check if memory freed or not. ). also, maybe worthy mention function arguments passed value in c, change make pp
(example: pp = null;
) not reflect ip
in main()
. free()
work normally, though.
also, please see discussion on why not cast return value of malloc()
, family in c
..
Comments
Post a Comment