dangling pointer, reason for value change after free()?
- by Aman Jain
In the following code segment, after free(x), why does y becomes 0?
As per my understanding, the memory in the heap that was being pointed to by x, and is still being pointed by y, hasn't been allocated to someone else, so how can it change to 0?
And moreover, I don't think it is free(x) that changed it to 0.
Any comments?
#include <stdio.h>
int main ( int argc, char *argv[] )
{
int *y = NULL;
int *x = NULL;
x = malloc(4);
*x = 5;
y = x;
printf("[%d]\n", *y); //prints 5
free(x);
printf("[%d]\n", *y); //why doesn't print 5?, prints 0 instead
return 0;
}