Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
What is a dangling pointer?
1.1.
Code in C
2.
Cause of Dangling Pointers
2.1.
When a pointer is initialized in a different scope.
2.2.
Having multiple pointers to the exact memory location.
2.3.
Returning the address of a stack-allocated variable from a function.
3.
How Dangling References and Pointers are avoided?
4.
Frequently Asked Questions
4.1.
What do you mean by Dynamic memory allocation?
4.2.
What are malloc and free?
4.3.
What is garbage collection in Java?
5.
Conclusion
Last Updated: Jun 27, 2024
Easy

Dangling Reference in Compiler Design

Author Nikhil Joshi
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

A dangling reference is a situation in compiler design where a pointer or reference points to a memory location that has been deallocated or released. This can happen when an object is deleted or goes out of scope, but the reference to it still exists and is later accessed.

A link or pointer to an instruction, table element, index item, etc. whose content has changed or no longer contains the same content. If the reference points to an invalid address or a valid address with no content, it may cause the computer to crash if the software is not programmed to handle such cases properly.

Dangling Reference in Compiler Design

This article, Dangling Reference in Compiler Design, will take you through dangling pointers, how they occur in our program and why they are a cause of concern. We will also look at different ways to get rid of dangling pointers.

What is a dangling pointer?

Dangling pointer points to the memory location that no longer contains the same content it used to hold.

In the C programming language, pointers are used to allocate memory using functions like malloc and calloc

  • These functions allocate memory dynamically to the pointers. After using pointers, we free the allocated memory to the respective pointer using the free function. 
  • This deallocation of the memory makes the deallocated memory available for reallocation to either the same program or a different program.
Deallocate Memory

We deallocated the memory using free or delete methods. This frees the memory to the compiler, and now it can allocate it again to either some variable or a completely different program. However, the problem is that we still have pointers that point to the exact memory location. These pointers can later access those locations and can corrupt data. 

We call such pointers the dangling pointer.

Let’s understand through a C code how dangling pointers get introduced in our program.

Code in C

#include <stdio.h>


int main() {
   
   // Declaring an integer pointer
   int * pointer = NULL;


   // Allocating pointer variable using malloc function
   pointer = (int *) malloc(sizeof(int));


   // Assigning value to the pointer variable
   *pointer = 5;


   // printing to show that pointer contain the correct content
   printf("Value stored in pointer is %d \n",*pointer);


   // Free the memory allocated to the pointer
   free(pointer);


   /*Now pointer is a dangling pointer
   It is a pointer to a memory location which is deallocated using free
   Let's try to print the pointer value now.
  */


   printf("After deallocation, we are again accessing pointer \n");
   printf("%d",*pointer);


   return 0;
}

Output

output

Explanation

  • We have declared an integer pointer and allocated memory using the malloc function. 
  • Later we store value(5) in it by dereferencing the pointer. 
  • We are printing the pointer's value to check if it contains the correct value. 
  • We deallocate the memory allocated to the pointer using the free function. 
  • We again checked the pointer's value, but it prints a garbage value showing that memory is deallocated.

Even after deallocating the pointer, we can access that memory location (we have the pointer pointed to that memory location) is a cause of major concern

The problem lies here..

It is possible that the compiler later allocates that portion of memory to some other variable. We have a pointer that can access the location of newly allocated memory; it can cause corruption in the data of the new variable. 

It is also possible that the deallocated memory may be allocated to some other program. If pointers try to access that location, the compiler will throw a Segmentation error

Our program may have some privilege of accessing the operating system code. In that case, dangling pointers can cause significant havoc and lead to discrepancies in the system.

Cause of Dangling Pointers

The following are some programming practices that can cause dangling pointers: 

When a pointer is initialized in a different scope.

In this example, we are going to define a separate scope. Inside this scope, we will make the pointer to point to some location and then see how it acts like a dangling pointer.
Code in C 

#include <stdio.h>


int main() {
   
   // Declaring an integer pointer
   int * pointer = NULL;


    // We are creating a separate scope
   {
       // creating an integer variable with value 13 in it
       int x = 13;
       
       // assigning pointer address of x
       pointer = &x;
       
       // printing value of the pointer to show its content
       printf("We are inside the scope\n");
       printf("Value of pointer is : %d \n",*pointer);
       
   }
   
   /* 
      x is out of scope now
      pointer is now a dangling pointer
      trying to access pointer value
    */
   printf("We are outside the scope \n");
   printf("Value stored in pointer is: %d",*pointer);


   return 0;
}

Output

output

We are outside the scope of 'x' but can still access its value. This can cause serious security problems in our programs.

Having multiple pointers to the exact memory location.

This example defines multiple pointers pointing to the same memory location. Later, we will free the memory location and set the pointer to null. In this case, other pointers will act like dangling pointers.

Code in C 

#include <stdio.h>


int main() {
   
   // Declaring an integer pointer
   int * pointer = NULL;
   
   // allocating memory to a pointer
   pointer = (int *) malloc(sizeof(int));
   
   // assigning a value to the pointer
   *pointer = 10;
   
   // assigning “other_pointer variable” to the pointer
   int * other_pointer = NULL;
   other_pointer = &pointer;
   
   // Checking both variable's value
   printf("Value of pointer is %d \n",*pointer);
   printf("Value of other_pointer is %d \n",*other_pointer);
   
   // Now deallocating the pointer variable
   free(pointer);
   pointer = NULL; // again making pointer as null
   
   /* After some more statements, business logic*/
   // programmer tried to access other_pointer
   
   *other_pointer = 99; // This statement can overwrite the content of some other variable
   
   
   return 0;
}

Output

output

Although we deallocate the memory, we still have “other_pointer” pointed to the memory location. If, in case, the compiler allocates the memory to some other variable, then using “other_pointer” can corrupt its data.

Returning the address of a stack-allocated variable from a function.

Here we are defining a pointer and initialising its value from the return value of another function which returns an address of a stack-allocated variable.

Code in C 

#include <stdio.h>


int * function(){
    int x = 19;
    // returning address of a stack variable
    return &x;
}


int main() {
   
   // Declaring an integer pointer
   int * pointer = NULL;
   
   // allocating memory to the pointer
   pointer = function();
   printf("%d",*pointer);
   
   return 0;
}

Output

output

Compilation of the program warned that we are returning the address of a local variable. The problem is we have a dangling pointer now. Later, if the compiler allocates that address to any other variable, its content can be corrupted using a dangling pointer.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

How Dangling References and Pointers are avoided?

There are different methods of avoiding dangling pointers in different programming languages.

  • In the C programming language, we can use an extended version of the free function which not only deallocates the memory allocated to a variable but also sets it to null. However, this does not make the program foolproof from dangling pointers.
  • In C++, we can make use of smart pointers. Smart Pointers use reference counting to reclaim the object.
  • Programming languages like Java do not allow deallocating memory; hence, there are no dangling pointers. They use garbage collection to reclaim objects.

Also check out - Phases of Compiler and  cousins of compiler

Frequently Asked Questions

What do you mean by Dynamic memory allocation?

Dynamic memory allocation is the process of allocating memory to the objects during runtime. In C, we use functions such as malloc and calloc. In C++ and Java, we have the new operator for dynamic memory allocation.

What are malloc and free?

malloc() and free() are the functions used for dynamic memory allocation and deallocation, respectively, in C. They use system APIs of the operating system to get or take memory from a pointer/reference. 

What is garbage collection in Java?

Garbage collection in Java is the process of removing unreferenced objects from the run-time memory space. Java does not allow the deallocation of memory. When no reference to an object remains, then the object is swept up from the memory by the garbage collector.

Conclusion

In conclusion, dangling references can cause great havoc in our programmes. They arise from faulty programming practices and sheer negligence and can cause security flaws in our program. The error related to dangling pointers is hard to locate in big software applications. Thus it is better to prevent our programs from using discussed methodologies.

Hope the article helped you provide great insight into Dangling Reference in Compiler Design. 

Refer to our guided paths on Code360 to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Happy Learning!

Previous article
Input Buffering in Compiler Design
Next article
Handle in Compiler Design
Live masterclass