× Home
Next Lec → ← Previous Lec

Null Pointer

What is a Null pointer?

NULL Pointer: C Program

  • A null pointer is a pointer that points to NULL (nothing)
  • A null pointer should not be dereferenced.
  • A check must be run by the C programmer to know whether a pointer is null before dereferencing it.
    • int x = 10;
    • int *p = NULL; // null pointer
    • p = &x; // null pointer now holds address of int 'x'

Use of NULL Pointers

  • To initialize a pointer variable in cases where pointer variable has not been assigned any valid address yet.
  • To check for legitimate address location before accessing any pointer variable.
  • By doing so, we can perform error handling while using pointers with C.
  • Example of such error handling can be: dereference pointer variable only if it's not NULL.
  • To pass a null pointer to function argument when we don't want to pass any valid memory address.

More on NULL Pointers

  • NULL macro is defined as ((void*)0) in header files of most of the C compiler implementations.
  • NULL pointer vs Uninitialized pointer - An unitialized pointer contains an undefined value.
  • A null pointer stores a defined value, which is the one decided by the environment to not be a valid memory address for any object.
  • NULL pointer vs Void Pointer → Null pointer is a value where as void pointer is a type
                            
                             #include <stdio.h>
                             int main()
                             {
                                int a = 34;
                                int *ptr = NULL; // when we dereference this value the program crashes so to stay safe we do
                                if (ptr != NULL) //for error handling
                                {
                                    printf("The value at ptr is %d", *ptr); // dereferencing to print the value
                                }
                                else
                                {
                                    printf("The pointer is a null pointer and cannot be dereferenced.");
                                }
                                printf("The address of a is %d", ptr);
                                return 0;
                             }