codey modey
codey modey

Reputation: 983

Unable to free a pointer from within a function

Following assert doesn't fails, though it should fail according to my understanding. Please correct me.

#include <stdio.h>
#include <assert.h>

void custom_free(int **temp){
      free(*temp);     
}

int main(){
    int *ptr = malloc(1024);
    custom_free(&ptr);
    assert(ptr); // doesn't fails ..why?
}

Upvotes: 1

Views: 62

Answers (2)

Frerich Raabe
Frerich Raabe

Reputation: 94299

You don't "free a pointer", but you can free the memory referenced by a pointer. And that's what free does: it doesn't modify the pointer, it only does something with what the pointer points to.

Your issue has nothing to do with whether the free call is done in a function or not. Try adding

*temp = 0;

after your free call to enforce that you get a null pointer.

Upvotes: 2

simonc
simonc

Reputation: 42165

Calling free doesn't change the value of a pointer. If you want to NULL freed memory you'll have to do it yourself

void custom_free(int **temp){
      free(*temp); 
      *temp = NULL;
}

Upvotes: 3

Related Questions