Could anyone explain dangling pointers with better programs.
Could anyone explain dangling pointers with better programs.
p = malloc( 10 );
free( p );
// p is now a dangly
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
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.
Hope is the first step on the road to disappointment.
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 */
Last edited by grumpy; 08-30-2005 at 06:27 AM.
thanks a lot