My question is, if the following sentence is true or false? why?
“It is important to deallocate a pointer to avoid dangling pointers.”
Thanks
Printable View
My question is, if the following sentence is true or false? why?
“It is important to deallocate a pointer to avoid dangling pointers.”
Thanks
Would you describe in your words how you understand "dangling pointer"?
My understanding of dangling pointer is,'when the memory to which pointer is pointing to, is deallocated then the pointer becomes dangling. Pointer also becomes dangling when you try to dereference uninitialized pointer.So programmer has to be very careful not to dereference dangling pointer otherwise unnecessary results occur.To avoid this one should set the pointer to NULL after deallocation of the memory it is pointing to.
'you never deallocate pointer but you deallocate memory it is pointing to' . So in my original question I have asked, the sentence used is 'deallocate a pointer' which is confusing me. It is the question in my assignment I have to write,the correct version of it, if it is wrong.
waiting for the reply
Thanks.
That is not what I would say a "dangling pointer is".
Look at this:
http://en.wikipedia.org/wiki/Dangling_pointer
--
Mats
So 'deallocating a pointer' means setting pointer's value to NULL?
Thanks
No, deallocating is calling free or delete. Setting the pointer to NULL is a preacaution to prevent the variable from being used accidentally AFTER it has been freed. [which is one form of dangling pointer - you have a pointer to memory no longer owned by the application].
--
Mats
Thank you so much
sorry, still confused little bit..
Now my understading is deallocating a pointer does not avoid dangling pointer because pointer value is not changed yet. after deallocation setting the pointer value to NULL only avoid dangling pointer..
Please correct me if I am wrong.
Thanks.
Correct, if you do not change the value of the pointer, then you do indeed have a dangling pointer - a pointer to memory that you do not own. Setting it to NULL does not deallocate the memory, it sets the pointer to a NULL value - which is the way to indicate that "this pointer is no longer pointing to valid memory, it is NULL and has no content".
--
Mats
Deallocating objects or "pointers" has to do with avoiding memory leaks. Naturally, since the object is not valid after it is deallocated, deallocation is a way to obtain, not fight dangling pointers.
Dangling pointers have the annoying tendency to not crash your program and instead silently corrupt data. That's why you set them to NULL, because dereferencing that will crash your program.Quote:
'undefined results' usually means your program will blow up on you with a segfault (windows = "access violation") and a crash.
Good point. Ultimately the program will probably crash but it could be well after the data a pointer was pointing to was freed. Those are the most annoying bugs to find if you're not familiar with a good debugger.