I've seen lots of code like this:
SomeType* ptr = NULL; ptr = SomeMethod(some, params);
What's the point? I've also seen it where ptr
is declared somewhere else (for example in a class definition) and then in the class constructor there'd be this:
ptr = NULL; ptr = SomeMethod(some, params);
I don't understand why this is done. Surely the ptr = NULL
line is useless?
After using free(ptr) , it's always advisable to nullify the pointer variable by declaring again to NULL. e.g.: free(ptr); ptr = NULL; If not re-declared to NULL, the pointer variable still keeps on pointing to the same address (0x1000), this pointer variable is called a dangling pointer.
It's good practice to check for null in function parameters and other places you may be dealing with pointers someone else is passing you. However, in your own code, you might have pointers you know will always be pointing to a valid object, so a null check is probably overkill... just use your common sense.
A null pointer has a reserved value that is called a null pointer constant for indicating that the pointer does not point to any valid object or function. You can use null pointers in the following cases: Initialize pointers. Represent conditions such as the end of a list of unknown length.
A pointer can't point to null. It can be a null pointer, which means it doesn't point to anything. And a declared object can't be deleted as long as its name is visible; it only ceases to exist at the end of its scope. &value is a valid address at the time the assignment nullPointer = &value; is executed.
if "SomeMethod" throws an exception your SomeType* will keep pointing to something you don't want it to point to. Hence it is definitely a good practice to set pointer to null if you don't want it to point to the old thing anymore.
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