De-allocation of memory
[pastacode lang=”cpp” manual=”%23include%3Cstdlib.h%3E%0Avoid%20main()%0A%7B%0A%20%20%20%20char%20*ptr%20%3D%20malloc(Constant_Value)%3B%0A%20%20%20%20free%20(ptr)%3B%20%2F%2Fptr%20now%20becomes%20a%20dangling%20pointer%0A%7D” message=”” highlight=”” provider=”manual”/]
- 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.
Function Call
[pastacode lang=”cpp” manual=”int%20*%20func%20(%20void%20)%0A%7B%0A%20%20%20%20int%20num%20%3D%2014%3B%0A%20%20%20%20return%20%23%0A%7D” message=”” highlight=”” provider=”manual”/]
- 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
[pastacode lang=”cpp” manual=”%23include%3Cstdlib.h%3E%0Avoid%20main()%0A%7B%0A%20%20%20%20char%20*ptr%20%3D%20NULL%3B%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20char%20ch%3B%0A%20%20%20%20%20%20%20%20ptr%20%3D%20%26ch%3B%0A%20%20%20%20%7D%2F%2Fdp%20is%20now%20a%20dangling%20pointer%0A%7D” message=”” highlight=”” provider=”manual”/]
- 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”.