Dangling Pointer in C

Here you will learn about dangling reference and dangling pointer in C.

In computer programming, memory is allocated for holding data object. After the work is done the memory is deallocated so that this memory can be used to store any other data object.

Also Read: void pointer in C

What is Dangling Pointer?

While programming, we use pointers that contain memory addresses of data objects. Dangling pointer is a pointer that points to the memory location even after its deallocation. Or we can say that it is pointer that does not point to a valid data object of the appropriate type. The memory location pointed by dangling pointer is known as dangling reference.

Now if we access the data stored at that memory location using the dangling pointer then it will result in program crash or an unpredictable behaviour.

Dangling Pointer in C

Let’s take an example to understand this.

 

Cause of Dangling Pointer in C

 

In above example we first allocated a memory and stored its address in ptr. After executing few statements we deallocated the memory. Now still ptr is pointing to same memory address so it becomes dangling pointer.

I have mentioned only one scenario of dangling pointer. There are many other situations that causes dangling pointer problem.

To read more you can visit: https://en.wikipedia.org/wiki/Dangling_pointer

 

How to Solve Dangling Pointer Problem in C?

To solve this problem just assign NULL to the pointer after the deallocation of memory that it was pointing. It means now pointer is not pointing to any memory address.

Let’s understand this by a code in C.

 

 

If you have any doubts related to above dangling pointer in C tutorial then feel free to ask by commenting below.

2 thoughts on “Dangling Pointer in C”

  1. Avinandan Sen Gupta

    Now if in this code–
    void function(){
    int n;printf(“enter no of integers to be entered–\n”);
    scanf(“%d”,&n);
    int i=0;
    int *ptr = (int *)malloc(n*sizeof(int));
    printf(“Enter numbers–\n”); //entry of an array of nos
    for(i=0;i<n;i++)
    scanf("%d",(ptr+i));
    printf("Entered numbers are–\n"); //displaying the entered nos
    for(i=0;i<n;i++)
    printf("%d",*(ptr+i));
    free(ptr); //ptr now becomes dangling pointer which is pointing to dangling reference
    }
    After free(ptr) statement i f i try to access the previously entered nos using ptr will it lead to program crash???

    Simply Speaking if after free(ptr) I type–
    printf("Entered numbers are–\n"); //displaying the entered nos
    for(i=0;i<n;i++)
    printf("%d",*(ptr+i));

    Will it display the entered nos or lead to unusual termination of Program??????

    Please help if u can!!!!!

Leave a Comment

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