- A dangling pointer is pointing to a memory location that has been deleted (or freed). The dangling pointer act as a different ways there are,
- De-allocation of memory
- Function Call
- Variable goes out of scope
De-allocation of memory
- First we have declared in the character pointer. After execution of some statements we have de-allocated memory which is allocated previously for the pointer.
- Immediately memory is de-allocated for pointer, pointer becomes dangling pointer.
- The pointer may be return the correct value (1234) for a while after calling func, but any functions called thereafter will overwrite the stack storage allocated for num with other values and the pointer would no longer work correctly.
- If a pointer to num must be returned, num must have scope beyond the function it might be declared as static.
Variable goes out of scope
- First we have declared in the Character Pointer.
- Next the Pointer Variable ‘ptr’ is pointing to Character Variable ‘ch’ declared in the inner block .
- As character variable is non-visible in Outer Block , then Pointer is still pointing to Same Invalid memory location in Outer block , then Pointer becomes “Dangling”.