-1

Why should i use pointer to pointer in my saferFree(void**) function when i want to free memory inside that 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 but below code with double pointer works properly.I want to 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;
    }
}
Zed
  • 416
  • 2
  • 7
  • 3
    What doesn't work? – Vilx- Jul 28 '16 at 08:04
  • 1
    Please show the part where you get to see `.It doesn't Free the allocated memory.` Some people are getting confused. – Sourav Ghosh Jul 28 '16 at 08:11
  • 1
    I suspect the problem is OP expects the pointer `ip` main() to be `NULL` because it's set to `NULL` in `safeFree()`. `pp` is local to `safeFree()`, so it doesn't reflect in main(). See this post as well: http://stackoverflow.com/questions/13431108/changing-address-contained-by-pointer-using-function – P.P Jul 28 '16 at 08:15

1 Answers1

0

FWIW, it is perfectly safe to pass NULL to free(). Your wrapper is basically meaningless.

Quoting C11, chapter §7.22.3.3, (emphasis mine)

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. [..]


That said, as per your question, it works fine, but because accessing free-d memory is UB, you should not be doing that (which you seem to be doing in main() after calling saferFree() to check if the memory is freed or not. ). Also, maybe worthy to mention that the function arguments are passed by value in C, so any change you make to pp itself (example: pp = NULL;) will not reflect to ip in main(). free() will work normally, though.

Also, please see this discussion on why not to cast the return value of malloc() and family in C..

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261