Null Pointer in C

In this tutorial you will learn about null pointer in C with examples.

When we declare a pointer, by default it points to some random memory location. If you will access the pointer then it may give some undesired value or the program may crash.

What is Null Pointer in C?

Null Pointer

A pointer pointing to nothing or no memory location is called null pointer. For doing this we simply assign NULL to the pointer.

So while declaring a pointer we can simply assign NULL to it in following way.

int *p = NULL;

NULL is a constant which is already defined in C and its value is 0. So instead of assigning NULL to pointer while declaring it we can also assign 0 to it.

Usage of Null Pointer

1. We can simply check the pointer is NULL or not before accessing it. This will prevent crashing of program or undesired output.

int *p = NULL;

if(p != NULL) {
//here you can access the pointer
}

2. A pointer pointing to a memory location even after its deallocation is called dangling pointer. When we try to access dangling pointer it crashes the program. So to solve this problem we can simply assign NULL to it.

void function(){
    int *ptr = (int *)malloc(SIZE);
    . . . . . .
    . . . . . . 
    free(ptr);    //ptr now becomes dangling pointer which is pointing to dangling reference
    ptr=NULL;    //now ptr is not dangling pointer
}

3. We can simply pass NULL to a function if we don’t want to pass a valid memory location.

void fun(int *p) {
    //some code
}

int main() {

    fun(NULL);

    return 0;
}

4. Null pointer is also used to represent the end of a linked list.

Linked List

Image Source

Comment below if you found anything incorrect or have queries regarding above tutorial for null pointer in C.

Leave a Comment

Your email address will not be published. Required fields are marked *