why can Dangling pointer not store any value and why does it throw 0? As it points to same memory which is freed. why 0 if we try to store some value?
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *p;
p=(int*)malloc(sizeof(int)*5);//allocating memory in heap
printf("%p\n",p);
free(p); //freeing memory
printf("%p\n",p); //still pointer same loaction(dangling pointer)
scanf("%d",p); // why cant i scan if it is still pointing same location
// i know memory is delete but why 0 is thrown?
printf("%d\n",*p);// i am getting zero here?
}
This is illegal memory accessing. The address should not be used after freeing.
After deallocating an address, set the pointer to NULL. So that the illegal memory accessing will be eradicated.
Example:
free(p);
p=NULL;