Difference between a null pointer, a void pointer and a dangling pointer

Frequently asked question in viva voce and interview.

Tue Sep 5, 2023

Mysterious Pointers 

"Pointers in C are like cats: They'll lead you on a wild chase, and just when you think you've got them, they'll playfully scratch your memory" 

Null Pointer:

A null pointer is a pointer that doesn't point to any memory location. It is used to indicate that the pointer does not currently refer to a valid object or memory location.


In this example, ptr is a null pointer because it doesn't point to any specific memory location.

Dangling Pointer:
A dangling pointer is a pointer that points to a memory location that has been deallocated or freed. Accessing or dereferencing a dangling pointer can lead to undefined behavior.
Example:
In this example, we first allocate memory for an integer using malloc. Later, we free this memory using free(ptr1). After that, ptr1 becomes a dangling pointer because it still contains the address of the previously allocated memory, which is no longer valid.
Attempting to access the value pointed to by the dangling pointer, as shown in the printf statement, can result in undefined behavior. This demonstrates the concept of a dangling pointer in C.

Void Pointer:

A void pointer is a pointer that does not have a specific data type associated with it. It can point to objects of any data type. It is often used in situations where the data type is unknown or can vary. For Example:

In this example, we declare a void pointer ptr. The key characteristic of a void pointer is that it can point to data of any data type. We use ptr to point to an integer, a float, and a character sequentially. When dereferencing the void pointer, we need to cast it to the appropriate data type to correctly access the value stored at that memory location.
This demonstrates the versatility of void pointers in C, allowing them to point to different types of data dynamically.

Next time I will cover constant pointer and it's applications in C, C++ and Python
 


Bhalchandra Gholkar
Educator, S/W developer, and Odoo ERP consultant