Tutorial Study Image

Null Pointers


September 14, 2022, Learn eTutorial
966

If you are unsure of the exact address to assign, it is always a good idea to assign the pointer NULL into a pointer variable. When a variable is declared, this is done. Null pointers are those to which NULL has been assigned.

iostream is one of the standard libraries that define the NULL pointer which is a constant with a value of zero. 

C++ NULL Pointer

Consider the following program for an example:

Example : NULL Pointer


#include <iostream>

using namespace std;
int main () {
   int  *ptr = NULL;
   cout << "The value of ptr will be " << ptr ;
 
   return 0;
}

Output:

The value of ptr will be 0

Because the operating system has reserved memory at address 0, most operating systems do not allow programs to access that memory. Memory address 0 has a specific meaning, however, as it indicates that the pointer is not meant to point to a memory region that is accessible. However, by convention, it is assumed that a pointer points to nothing if it has the null (zero) value.

You can use an if statement to check for a null pointer as seen below.


if(ptr) // succeeds only if the  p is not null
if(!ptr) // succeeds only if the p is null
 

Therefore, you can prevent the unintentional usage of a null pointer if all unused pointers are assigned the null value and you can avoid using a null pointer. Uninitialized variables often include junk values, making it more challenging to debug the program.