free() function

Hello everyone I am new to the forum and I was trying to deepen my knowledge on c, in particular I'm seeing the free() function , and I wondered why in this code when I use free (ptr); never becomes NULL ptr

thank you very much

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include <stdlib.h>

  int main(){    
    int *ptr;
    ptr= (int*) malloc (sizeof (int));
    *ptr = 2;
    
    free(ptr);
    if (ptr==NULL){
        printf("freed memory \n");
    }else {
        printf("memory is not freed\n");
    }
    
    
    return 0;
}
free() deallocates the memory as you expect, but does not update the pointer, there could be many pointers pointing at the memory, its for you to set them to NULL.

1
2
free(ptr);
ptr = NULL;

thanks Jaybob66,
so it is for the same reason (the pointer update) that print: 2 if I write:

 
printf ("% d \ n", * ptr); 


after
 
free(ptr);

that's right?
Topic archived. No new replies allowed.