I don't get why the free here is not working and i still get 5 in the printf. Should i just point the p value to NULL? I've searched many threads but didn't find any helpful informations about this.
#include<stdio.h>
void main(){
int *p = malloc(sizeof(int));
*p = 5;
free(p);
printf("%d\n",*p);
}
CodePudding user response:
The function is called free
not erase
, it does not "erase" the memory pointed by the pointer, it merely allows that area of memory to be used for something else. printf
printed the previous value, meaning that nothing else happened to use the memory that has been just freed.
Regardless, you are still attempting to access a memory that no longer belongs to you, and hence invoking undefined behaviour. The code may crash, or print the previous value, or print garbage, or it might as well draw a unicorn to the console, this is what makes undefined behaviour ...undefined.