Could anyone explain dangling pointers with better programs.
Printable View
Could anyone explain dangling pointers with better programs.
p = malloc( 10 );
free( p );
// p is now a dangly
what actually happens here
If you don't try using p again without allocating more space, or pointing it at something valid, nothing. If you do try using it without allocating more space, or pointing it at something valid, BadThings(TM) happen.
Quzah.
The scenario is that the pointer initially points at an object. The object ceases to exist, but the value of the pointer does not change. The pointer is "dangling" because it points at an object that no longer exists.
In the example given by salem, the call to free() causes the block of memory pointed at by p to be released. The call to free(p), however, does not change the value of p.
another example is
}Code:int *func()
{
int x;
x = 42;
return &x; /* x ceases to exist when function returns */
}
int main()
{
int *y = func();
*y = 100; /* y is a dangling reference, so this line yields undefined behaviour */
thanks a lot