Dangling Pointers in C/C++

Share Your Love

Dangling/wild pointers are the most common pointer and memory management problems. A dangling pointer is a sort of initialized pointer in C that occurs when the programmer fails to initialize the pointer with a proper location.

When an object is removed or de-allocated from memory without changing the value of the pointer, it becomes a dangling pointer.

The pointer in this scenario is pointing to a memory that has been de-allocated. The dangling pointer can point to a memory location that contains either application code or operating system code.

If we provide this pointer with a value, it overwrites the value of the program code or operating system instructions; as a result, the program will produce an unpleasant outcome or even crash. If the memory is re-allocated to another process, segmentation faults will occur if we dereference the dangling pointer.

Let’s observe the following examples:

dangling pointer
Dangling Pointer

We can see that Pointer 3 is a dangling pointer in the diagram above. The pointers Pointer 1 and Pointer 2 point to the allocated objects, Object 1 and Object 2, respectively. Because it points to the de-allocated object, Pointer 3 is a dangling pointer.

Let’s look at several C programs to see how the dangling pointer works:

To de-allocate memory, use the free() method.

#include <stdio.h>  
int main()  
{  
   int *ptr=(int *)malloc(sizeof(int));  
   int a=560;  
   ptr=&a;  
   free(ptr);  
   return 0;  
}  

We’ve defined two variables, *ptr and a, in the above code, where ‘ptr’ is a pointer and ‘a’ is an integer variable. The *ptr variable is a pointer variable generated with the malloc() method. We use int * to convert a void pointer to an int pointer because the malloc() operation returns a void.

The statement int *ptr=(int *)malloc(sizeof(int)); will allocate the memory with 4 bytes shown in the below image:

malloc memory alloc
Dynamic Memory Allocate

The statement free(ptr) de-allocates the memory as indicated below with a cross sign, and the ‘ptr’ pointer dangles as it points to the de-allocated memory.

dangling pointer after delete
Memory De-allocate

If we provide the ‘ptr’ variable with a NULL value, it will not point to the removed memory. As a result, we can conclude that ptr is not a dangling pointer, as depicted in the diagram below:

not dangling pointer
Not Dangling Pointer

Variable goes out of the scope

When a variable is no longer in scope, the pointer pointing to it becomes a dangling pointer.

#include<stdio.h>  
int main()  
{  
    char *str;  
    {  
        char a = 'A';  
        str = &a;  
    }  
    // a falls out of scope   
    // str is now a dangling pointer   
    printf("%s", *str);  
}  

In the above code, we know the following points:

  • First, we declare the ‘str’ pointer variable.
  • We declare a character variable in the inner scope. The address of the variable ‘a’ is stored in the ‘str’ pointer.
  • The ‘a’ is variable will no longer be available when the control exits the inner scope, thus ‘str’ points to the de-allocated memory. The ‘str’ pointer becomes the hanging pointer as a result.

Function call:

Now we’ll look at how the pointer becomes dangling when the function is called.

Let’s understand through an example.

 #include <stdio.h>  
 int *fun()
 {  
    int y=10;  
    return &y;  
  }  
int main()  
{  
int *p=fun();  
printf("%d", *p);  
return 0;  
}  

In the above code, we did the following steps:

First, we build the main() function, where we define the ‘p’ pointer, which contains the return value of the ‘fun()’

The control passes to the context of the int *fun() when the fun() is called, and fun() returns the address of the ‘y’ variable.

The variable ‘y’ is no longer available when control returns to the context of the main() function. As a result, the ‘p’ pointer is a dangling pointer since it points to unallocated memory.

Output:

Segmentation Fault

Let’s represent the working of the above code below figure.

dangling pointer segmentation fault
Segmentation Fault

The fundamental reason for this is that when a function is called, the compiler always creates a stack. When a function exits, the function stack is likewise erased, and the local variables of the function are no longer in scope.

Let’s look at another dangling pointer scenario.

#include <stdio.h>  
int *fun()  
{  
    static int y=10;  
    return &y;  
}  
int main()  
{  
   int *p=fun();  
   printf("%d", *p);  
    return 0;  
} 

Output:

10

Static variables have the ability to retain their value even after they have been moved from their scope. To implement the concept of returning a pointer from a function in C, the local variable must be declared as a static variable.

Now we’ll draw a graph to show how the aforementioned code works.

stack variable in dangling pointer
Static Variable With No Dangling Pointer

The stack memory is depicted in the diagram above. The control moves to the context of the int *fun() after the fun() method is called.

Because ‘y’ is a static variable, it is stored in global memory and is accessible throughout the program. When the address value is returned, the control is returned to the main() context.

The address of ‘y’ is contained in the pointer ‘p,’ which is 100. When we print the value of ‘p,’ it also prints the value of ‘y,’ which is 10, in this case. As a result, we can argue that the pointer ‘p’ is not a dangling pointer because it includes the address of the global memory variable.

Avoiding Dangling Pointer Errors:

It is possible to avoid dangling pointer errors by setting the pointer to NULL. The pointer will not point to the de-allocated memory if the NULL value is assigned to it. When a pointer is given the value NULL, it indicates that the pointer is not pointing to any memory location.

Please share your opinion and wants to improve contact us.

Share Your Love
Default image
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Co-founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 343

Newsletter Updates

Enter your email address below to subscribe to our newsletter