Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any point to temporarily making a pointer NULL?

Tags:

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?

like image 895
Bertie Wheen Avatar asked Jan 28 '13 19:01

Bertie Wheen


People also ask

Should you set a pointer to NULL after freeing it?

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.

Should you always check if a pointer is null?

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.

What is the point of a null pointer?

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.

Can you point to a null pointer?

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.


1 Answers

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.

like image 154
sumeet Avatar answered Sep 20 '22 16:09

sumeet