In this blog, we will learn about dangling pointer in c, various ways where we can make a normal pointer act as a dangling pointer, followed by various methods to avoid making dangling pointer in c. We will learn all about dangling pointers while moving further with in the blog.
What is Dangling Pointer in C
A dangling pointer in C is a pointer that references memory that has been deallocated, such as a dynamically-allocated block of memory that has been freed. Dereferencing a dangling pointer can lead to undefined behavior or a segmentation fault. In simple words dangling pointer in c refers to or points to the memory which has been already deallocated such as dynamic memory which is not in use or deallocated.
When an object, variable, or memory location is removed or deallocated without changing the value of that specific pointer, these pointers are created.
Numerous frequent flaws in the C standard that involve C pointers are caused by the pointers and handling of the dangling pointers. It happens frequently for a programmer or developer to forget to initialize the pointer with a legitimate address. A dangling pointer in c is the term for that kind of initialized pointer.
Mostly dangling pointer in c comes when we are destructing an object.
How does Dangling Pointer in C work?
The dangling pointer in c can always point to a memory region or variable that contains the whole application code or the operating system’s code. The operating system or application code will replace any value that has been set to the dangling pointer in c, which will always have an unpleasant outcome or even cause the program to crash.
The segmentation fault will result in the dereference of the dangling pointer in c
if the memory is later relocated to another piece of code. The dangling pointer in c value won’t ever be changed, thus it could still refer to the location of the other deallocated memory.
The dangling pointer in c can be created when we do not modify the value of the pointer after the variable goes out of scope or deallocation memory.
Dangling Pointer is Created
There are generally three ways to create dangling pointers in c we will discuss all of them in this section of the article.
-
De-allocation of Memory
The allocation and deallocation of memory blocks are carried out using library functions, such as malloc(), calloc(), and free(). The former is used to allocate a memory block, while the latter is carried out using the former. Therefore, the pointer will behave as a Dangling Pointer in c when we deallocate a memory block using the free() method without changing the pointer value.
The only input for the free() method is a pointer referring to the memory that has to be deallocated.Example
#include <stdio.h> #include <stdlib.h> int main() { int *ptr = (int *)malloc(sizeof(int)); // normal pointer *ptr = 15; // memory block deallocated using free() function free(ptr); // here ptr acts as a dangling pointer printf("%d", *ptr); }
Output
0
Explanation of the above code
In the above example, we declared a pointer dynamically using malloc and after that, we freed the pointer after freeing the pointer we have not initialized it with null or anything so now that pointer will be a dangling pointer in c.
First, using the malloc() method, a memory block of sizeof(int) (typically 4 bytes) has been given to an integer pointer ptr. Right now, it functions like a typical pointer. The number 10 has been put into the integer memory block referred to by ptr. The 4 bytes of memory referred to by the ptr pointer and holding the value 15 are then deallocated by free(ptr). Due to the fact that ptr is currently pointing at a deallocated memory block, it will behave as a dangling pointer. and -
Function Call
When a variable is declared inside a function, it becomes local to that function’s execution and cannot be accessible from outside of that function. Now, imagine that the main() function’s pointer stores the address of that local variable inside the function. In this case, we can access the address of that local variable while the function is running, but when the function is finished, all internal variables go through garbage collection and are no longer in memory, but the main() function’s pointer is still pointing to that specific address, which is no longer available in memory, creating a dangling condition and would cause an error. So this will create a dangling pointer in c. And we cannot access that variable and the pointer pointing to that variable is known as a dangling pointer in c.Example
In this section, we will discuss an example of creating a dangling pointer in c using a function call.Code Implementation:
#include <stdio.h> int *danglingPointer() { int x = 15; return &x; } int main() { int *ptr = danglingPointer(); printf("%d", *ptr); return 0; }
Output
Runtime error
Explanation of the above Code
In the above example, we have seen that we have created a function using a pointer and then we have freed the memory using flash after that, we have seen the value of the pointer and that pointer has now become a dangling pointer in c and hence the output is shown accordingly. -
Variable Goes out of the Scope
In this section, we will see how can we create a dangling pointer in c when a variable goes out of scope. A variable will have a local scope and be destroyed after the inner block’s execution is complete if it is declared inside some inner code block. It will behave as a Dangling Pointer in c outside the inner block of code if the address of this local variable is assigned to a pointer declared outside the scope.Example
Here we will look at the example of the dangling pointer in c when we create a dangling pointer in c in the cases when a variable goes out of the scope.Code Implementation:
// Variable goes out of scope #include <stdio.h> int main() { int *ptr; { int temp = 22; ptr = &temp; // acting as normal pointer } // now ptr is a dangling pointer printf("%d %d", *ptr, temp); // prints garbage value printf("%d", *ptr); return 0; }
Output
prog.c: In function ‘main’: prog.c:15:27: error: ‘temp’ undeclared (first use in this function) printf("%d %d", *ptr, temp); ^~~~ prog.c:15:27: note: each undeclared identifier is reported only once for each function it appears in
Explanation of the above code
It is known as a Wild Pointer because, in the first step, we defined an integer pointer, ptr, without initializing it.
The second stage included inserting a code block with a restricted scope inside of which an integer variable named temp was defined and whose scope lasted only as long as the block was still being executed. The ptr pointer now refers to the location of the temp and has the address of the temp allocated to it. Assume that the temp has been assigned the base address 1000.
The memory used by temp has been deallocated by the operating system since it was declared inside this block, while ptr remains untouched because it is defined in the outside block of code.
The address 1000 is still there in ptr at step three, but there is nothing there. As a consequence, the pointer will become a "Dangling Pointer in c."
Since the temp variable is no longer in memory, we are unable to change its value with the ptr pointer.
Methods to Avoid Errors in Dangling Pointer in C
There are three main ways to avoid errors in dangling pointers in c. In this section we will discuss all of them:
- Perform de allocation of memory blocks using free() method.
To prevent the dangling pointer issue in our software, we should assign NULL to the ptr pointer as soon as the memory block referenced to by the ptr has been deallocated using the free() method. - Variable having limited scope during a function call
Static variables are those that stay in memory throughout the course of a program’s execution. In our application, we may declare a static variable by using the static keyword. - Varibles can go out of scope if declared inside some inner block of code
By employing strategies like setting NULL to the pointer as soon as the memory is deallocated and using static variables, which keep the variable in memory until the programme has finished running, we may prevent such issues.
Conclusion
In this blog, we have studied dangling pointer in c, followed by how dangling pointer is made, and how dangling pointer worked. A dangling pointer in C is a pointer that points to memory that is no longer valid. This can occur when a memory block is dynamically allocated, but the pointer to that block is not properly deallocated before the memory is freed. This can lead to undefined behavior, such as accessing uninitialized memory or causing a segmentation fault. To avoid dangling pointers, it is important to properly manage memory allocation and deallocation and to be aware of the lifetime of dynamically allocated memory.