In another question, I found out that the Assigned()
function is identical to Pointer <> nil
. It has always been my understanding that Assigned()
was detecting these dangling pointers, but now I've learned it does not. Dangling Pointers are those which may have been created at one point, but have since been free'd and haven't been assigned to nil
yet.
If Assigned()
can't detect dangling pointers, then what can? I'd like to check my object to make sure it's really a valid created object before I try to work with it. I don't use FreeAndNil
as many recommend, because I like to be direct. I just use SomeObject.Free
.
Access Violations are my worst enemy - I do all I can to prevent their appearance.
The dangling pointer errors can be avoided by initializing the pointer to the NULL value. If we assign the NULL value to the pointer, then the pointer will not point to the de-allocated memory. Assigning NULL value to the pointer means that the pointer is not pointing to any memory location.
When a pointer is pointing at the memory address of a variable but after some time that variable is deleted from that memory location while the pointer is still pointing to it, then such a pointer is known as a dangling pointer and this problem is known as the dangling pointer problem.
Dangling Pointer occurs when a pointer pointing to a variable goes out of scope or when an object/variable's memory gets deallocated. Also, the occurrence of Dangling Pointers can result in some unexpected errors during the execution of a program, so we have to make sure to avoid them while writing a program.
On a Linux system, a memory fault is called a segmentation fault. When a memory fault occurs, the OS terminates the process immediately. A dangling pointer is a pointer to memory that your program should not use. There are a few forms that a dangling pointer can have.
If you have an object variable in scope and it may or may not be a valid reference, FreeAndNil is what you should be using. That or fixing your code so that your object references are more tightly managed so it's never a question.
Access Violations shouldn't be thought of as an enemy. They're bugs: they mean you made a mistake that needs fixed. (Or that there's a bug in some code you're relying on, but I find most often that I'm the one who screwed up, especially when dealing with the RTL, VCL, or Win32 API.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With