dangling pointer, reason for value change after free()?
Posted
by Aman Jain
on Stack Overflow
See other posts from Stack Overflow
or by Aman Jain
Published on 2010-04-01T07:19:23Z
Indexed on
2010/04/01
7:23 UTC
Read the original article
Hit count: 276
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;
}
© Stack Overflow or respective owner