Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Difference between Null Pointer and Dangling Pointer

Last Updated on March 20, 2023 by Prepbytes

C and C++ is one of the most commonly used and popular programming languages available. There are many useful features available in this programming language and the pointer is one of those features. They are widely used as they provide a way to directly manipulate the memory and are also used in many programming paradigms like data structures, and dynamic memory allocation. Pointers can also lead to some bugs in the code if they are not used properly and have not been taken care of after their use. Some of the common errors are null pointers and dangling pointers. By the end of the article, you will have a complete idea of the difference between a null pointer and a dangling pointer.

Null Pointers

These are the type of pointers that do not point to a valid memory address. Instead, they point to a special value which is known as a null pointer value. In programming languages like C and C++, these values are represented by 0 or a constant NULL. They are usually used to indicate that a pointer is not currently pointing to a valid memory address or to initialize pointers to a known value.

The process when the program tries to the memory location of the pointer and uses the value at that particular memory location is known as dereferencing. So when a null pointer is dereferenced an access violation error or segmentation fault will occur. This is because the null pointer is not associated with any valid memory address so any attempt to access that address will result in a memory access violation.

Example of Null Pointer

Now we will look at an example of the null pointer with its code implementation.

#include <stdio.h>
 
int main(void) {
int* ptr = NULL;
*ptr = 10;
 
}

Output

Segmentation Error

Explanation of the above code
In the above example we have created a null pointer ptr and then try to assign the value 10 to the memory location pointed by it. But ptr is a null pointer so it does not point to any valid memory address and when you try to dereference it segmentation fault error will occur.

Dangling Pointers

A dangling pointer is a type of pointer that points to a memory location that has been deallocated or otherwise freed. When you have deallocated memory block then the memory is returned to the system and the program will not be able to access that memory any longer. And if the pointer still points to that memory location it becomes a dangling pointer.
There are many problems associated with dangling pointers depending on how they are used. In some cases, it can cause segmentation fault error or access violation error when trying to deference them just like a null pointer. By simplifying the above statement the program may continue to run but it will give unexpected or incorrect results.

Example of Dangling Pointer

In this section, we will see an example of dangling pointer with code and implementation.

#include <stdio.h>

int main(void) {
int* ptr = (int*) malloc(sizeof(int));
*ptr = 10;
free(ptr);
*ptr = 20;
    return 0;
}

Output

sample.c: In function 'main':
sample.c:4:19: warning: implicit declaration of function 'malloc' [-Wimplicit-function-declaration]
 int* ptr = (int*) malloc(sizeof(int));
                   ^~~~~~
sample.c:4:19: warning: incompatible implicit declaration of built-in function 'malloc'
sample.c:4:19: note: include '' or provide a declaration of 'malloc'
sample.c:6:1: warning: implicit declaration of function 'free' [-Wimplicit-function-declaration]
 free(ptr);
 ^~~~
sample.c:6:1: warning: incompatible implicit declaration of built-in function 'free'
sample.c:6:1: note: include '' or provide a declaration of 'free'

Explanation of the above code
This code dynamically allocates a block of memory large enough to hold an integer using the malloc function and then assigns the value 10 to the memory location pointed to by ptr. Next, the free function is called to deallocate the memory block pointed to by ptr. Finally, the program attempts to assign the value 20 to the memory location pointed to by ptr.

Since the memory block pointed to by ptr has been deallocated, ptr is now a dangling pointer. Attempting to dereference it (i.e., assigning the value 20 to the memory location pointed to by ptr) will result in undefined behavior. In some cases, this may cause the program to crash or produce incorrect results.

Difference Between Null Pointer and Dangling Pointer

In this section we will see various differences between a null pointer and a dangling pointer.

Parameter Null Pointer Dangling Pointer
Definition The pointer which does not point to a valid memory location. The pointer points to the deallocated memory location.
Dereferencing results in segmentation fault error. Dereferencing results in unexpected behavior which will lead to unexpected errors and program crashes.
Pointer Value Always has a defined null pointer value (typically 0 or NULL) Points to a memory location that may contain any value or may no longer exist
Memory Access Accessing memory through a null pointer always results in an access violation or segmentation fault Accessing memory through a dangling pointer can sometimes succeed without any issues, but can also lead to program crashes or unexpected behavior
Pointer Arithmetic Not allowed Not allowed
Pointer Comparison Only be compared to other null pointers Can be compared to any pointer.
Initialization Can explicitly set the pointer as null pointer Hace originated from incorrect memory management.
Detection Easy to detect Not easy to detect
Prevention We can prevent null pointers by initializing every pointer to a valid memory address. They can be prevented by properly dereferencing the pointers.
Usage Used to represent an invalid or uninitialized pointer Dangling pointers are typically the result of incorrect memory management and should be avoided in all cases

Conclusion
Null pointers and dangling pointers are two common errors that occur when we are dealing with pointers in programs of languages like C and C++. They both can produce errors and unexpected results they both are different in their initialization, behaviors, and causes. They both have different scenarios for occurrence. To prevent these from happening we can always assign the pointer to a valid memory address during initialization. We have understood the difference between a null pointer and a dangling pointer in detail. By understanding these pointers programmers can write safer and more reliable code.

Frequently Asked Questions

Here are some of the frequently asked questions about the difference between a null pointer and a dangling pointer.

1. Can you perform pointer arithmetic on null pointers?
No, pointer arithmetic is not allowed on null pointers.

2. What happens when you free a dangling pointer?
When you free a dangling pointer, you can get undefined behavior, which can lead to program crashes, memory corruption, or other unexpected results.

3. Can you have a null reference in C++?
No, C++ does not have null references. References are always expected to refer to a valid object.

4. Can a pointer be both null and dangling at the same time?
No, a pointer cannot be both null and dangling at the same time, as a null pointer does not point to any memory location, and a dangling pointer points to a memory location that has been deallocated.

5. Can you use a dangling pointer to access memory?
You can sometimes use a dangling pointer to access memory without any issues, but it can also lead to program crashes or unexpected behavior.

Leave a Reply

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