c - Why my free() wrapper function doesn't work? -


this question has answer here:

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 pointed ptr deallocated, is, made available further allocation. if ptr 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

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -