Pointers that point to invalid addresses is called dangling pointers.
Some Examples that causes dangling pointers:
- Casting arbitrary integers to pointers
Adjusting pointers beyond the bounds of arrays
Deallocating storage that one or more pointers still reference
C code/example of dangling pointers:
Code:
somefunc(){
x=(int *)malloc(sizeof(int));
...
free(x);
return (x); /* x is dangling pointer */
}
To avoid dangling pointers always assign NULL in C after freeing memory:
Code:
...
free(x);
x=NULL;
....