Dangling Pointer in C

Learn via video course
FREE
View all courses
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
Topics Covered

Overview

The pointers pointing to a deallocated memory block are known as Dangling Pointers. This condition generates an error known as Dangling Pointer Problem. Dangling Pointer occurs when a pointer pointing to a variable goes out of scope or when an object/variable's memory gets deallocated.

Also, the occurrence of Dangling Pointers can result in some unexpected errors during the execution of a program, so we have to make sure to avoid them while writing a program.

There are ways to avoid Dangling Pointer Problems like assigning NULL to the pointer when the memory gets deallocated or by using static variables.

Before reading this article, you should have some understanding of the following C Programming topics:

Introduction to Dangling Pointers in C

In general, Dangling means to hang freely. So as the name suggests, Dangling Pointers are the pointers that point to some freed/deleted location from the program's memory (memory that is currently not in the use of the program). When we talk about allocation and deallocation of memory blocks, we see Dynamic Memory Allocation concepts. In Dynamic Memory Allocation, generally, we use malloc(), calloc() functions to allocate a memory block and free() function to deallocate a memory block in C Language. So, once we deallocate a memory block using the free() function, a Dangling Pointer is generated.

To understand it better, consider a scenario where a person living in country A (for example) decides to move to country B for his/her vacations, where certain services like YouTube are not accessible. Now, whenever he/she tries to hit www.youtube.com, they would receive some HTTP errors, which means that there is no pointer or route available for www.youtube.com at that location. This could be analogous to a dangling pointer.

Let us now see how a dangling pointer works.

How does Dangling Pointer in C work?

Dangling Pointers are generated when we do not modify the value of a pointer after deallocation of a memory block or when a variable goes out of scope.

Let us now look at a diagram which represents how a dangling pointer is created. Here, memory occupied by an integer variable is deallocated, and the pointer pointing to the deallocated memory acts as a Dangling Pointer (hanging freely).

Dangling pointers representation

  • An integer pointer ptr points to an integer variable with value 5, ptr contains the address of the variable.
  • When the integer variable gets deallocated from memory, ptr shifts from a regular pointer to a Dangling Pointer, and it points to some Invalid / Not in use location.

Now, let us see the different ways where pointers act as dangling pointers in C Language.

Different ways where pointers act as Dangling Pointers in C

There are three different ways in which a pointer can act as a dangling pointer in C :

  1. Deallocation of memory
  2. Function Call
  3. Variable goes out of scope

Let us see all the three cases with some examples :

1. De-allocation of memory.

Allocation and deallocation of memory blocks are performed using library functions, like malloc(), calloc() functions are used for allocating a memory block, while free() function is used to deallocate a memory block. So, When we deallocate a memory block using free() function and do not modify the pointer value, it will cause the pointer to act as a Dangling Pointer.
The free() function takes a single parameter, i.e. a pointer pointing to the memory to be deallocated.

The diagram below shows how a dangling pointer is created in case of the deallocation of memory. De-allocation of memory

  1. An integer pointer ptr points to an integer variable with value 10, ptr contains the address of the variable allocated dynamically using malloc() method.
  2. When the integer variable gets deallocated from memory using the free(ptr); function, ptr points to some garbage value i.e. invalid location/data and acts as a dangling pointer.

Let us see the program for deallocation of memory in C Language using free() function.

C Program :

Output :

Example :

Explanation :

In this program, we can see that

  • First, an integer pointer ptr has been assigned a memory block of sizeof(int) (generally 4-bytes) using malloc() function. It is acting as a normal pointer for now.
  • Integer memory block pointed by ptr has been assigned value 10.
  • Next, free(ptr) deallocates the 4-bytes of memory space (containing value 10) pointed by the ptr pointer.
  • Now, ptr will act as a Dangling Pointer because it is pointing to some deallocated memory block.

2. Function Call

If we declare a variable inside a function, then that variable will be local to that function execution and cannot be accessed outside that function's scope. Now, suppose main() function's pointer stores the address of that local variable inside the function, this way we can access address of that local variable as long as the function is executing, but once the function execution gets over, all internal variables goes to garbage collection and are not in memory anymore, but main() function's pointer is still pointing to that particular address which is now not available in memory, hence creating a dangling condition and would be called as a Dangling Pointer.

The below diagram shows how a dangling pointer is created in case of a function call.

  1. A function() is called inside the main() function, memory is allocated by the system for the function() block.
  2. A local variable temp is declared and initialized inside the function(). Let the address of temp is 2000. After returning the address of the temp variable function execution finishes and temp also gets deleted from the memory.
  3. Returned address 2000 is stored in ptr pointer but as temp is not there in the memory anymore, ptr points to some garbage value and acts as a dangling pointer.

Function Call

For example, we return a local variable from the function call and how the pointer turns out to be a Dangling Pointer.

C Program :

Compilation Warning :

Output :

Example :

Explanation :

In this program, we can see that

  • First, an integer pointer ptr has been assigned a function call of the danglingPointer() function.
  • Now, danglingPointer() is invoked and execution of the function starts. danglingPointer() has a return type of int * i.e. the function will return an address of an integer block that can be stored in an integer pointer.
  • Inside the danglingPointer() function, we have an integer variable temp with local scope, temp has been assigned a value of 10. Now, we are returning the address of the temp variable and after returning the address, memory occupied by the danglingPointer() function will be deallocated along with the temp variable.
  • Now, the control will come back to main() function, and we have an address stored in ptr pointer, which is pointing to some deallocated memory (previously occupied by temp variable).
  • ptr is now acting as a Dangling Pointer because it is pointing to the deallocated memory block.

3. Variable goes out of scope

If a variable is declared inside some inner block of code, then the variable will have a local scope, and it will be deleted once the execution of the inner block ends. If the address of this local variable is assigned to a pointer declared outside the scope, then it will act as a Dangling Pointer outside the inner block of the code.

The diagram below shows how a dangling pointer is created in case an integer variable goes out of scope.

  1. A pointer ptr is declared in the main() function, it is acting as a wild pointer.
  2. When we enter the inner block of code, ptr points to the temp variable having value 10. temp has local scope and will be deleted from the memory as soon as the program control moves out of the inner block.
  3. temp goes out of scope and ptr still contains the address of deleted memory. So, ptr will point to some garbage value and will act as a dangling pointer.

Variable goes out of scope

Let us now see one example code where a variable goes out of scope.

C Program :

Compilation Error:

If we comment line 19 i.e. printf("%d %d", *ptr, temp); in the code, printf("%d", *ptr); prints some garbage value in output.

Example:

Explanation :

  • In the first step, we have declared an integer pointer ptr without the initialization, and it is referred to as a Wild Pointer.
  • In the second step, we have entered an inner block of code which has some limited scope, an integer variable temp is declared inside this block and have the scope until the execution of the block ends. Now, the address of temp has been assigned to the ptr pointer, and it points to the location of temp. Let's suppose 1000 is the base address where temp has been allocated.

When the scope of this block ends, ptr remains unaffected as it is declared in the outer block of code, while the memory occupied by temp has been deallocated by the operating system as it is declared inside of the block.

  • Now at the third step, ptr still contains the address 1000, but we have nothing at this location. This will result in the pointer known as a Dangling Pointer.
  • Now that the temp variable is not anymore in the memory, we can't modify the value of temp using the ptr pointer.

Let us now see how we can avoid the Dangling Pointers Problem in our programs.

How to avoid Dangling Pointer Errors in C

We have seen three ways where Dangling Pointers can be created.

  • Deallocation of memory blocks performed using free() method.
  • Variable having limited scope during a function call.
  • Variable goes out of scope if the variable is declared inside some inner block of code.

We can avoid these conditions by assigning NULL in case of deallocation of memory and using static variables in case of variables having local scope.

1. Assigning NULL after De-allocation of memory

We should assign NULL to the ptr pointer as soon as the memory block pointed by the ptr has been deallocated using the free() function to avoid creating the dangling pointer problem in our program.

The diagram below shows our algorithm's flow to assign NULL in a pointer as soon as the memory is deallocated.

Assigning NULL after De-allocation of memory

  1. An integer memory block is allocated using the malloc() function to the ptr pointer, and then we assign 5 to the memory block pointer by ptr pointer.
  2. free(ptr); deallocates the integer memory block pointed by ptr pointer, ptr now points to some garbage value in the memory.
  3. As soon as the memory is deallocated using free(), we assign NULL in the ptr pointer. It helps to avoid segmentation fault errors and garbage values.
  4. ptr = NULL; ensures that ptr is not a dangling pointer anymore.

Let us see the code to assign NULL to ptr after the deallocation of memory.

C Program :

Output :

Explanation :

  • First, We have allocated an integer memory block of 4-bytes using malloc() during runtime in the ptr pointer.
  • Value 5 has been assigned to the memory block pointed by ptr.
  • Using free(ptr), we have deallocated the memory block pointed by ptr.
  • printf("%d\n", *ptr); will print some garbage value as we have already freed the memory pointer by ptr.
  • We have added a statement ptr = NULL in the code. This ensures that the compiler knows ptr pointer is not a Dangling Pointer anymore and contains a defined value NULL. This pointer is known as a Null Pointer.
  • Now, printf("%d", *ptr); will print nothing as ptr is NULL and program exits with runtime error since we are trying to access memory that does not exist.

2. Static variables with global scope

Static variables are the variables that remain in the memory until the execution of the program finishes. We can use the static keyword to declare a static variable in our program.

Syntax :

x is a static integer variable with global scope and will stay in the memory until the execution of the program finishes. Global scope means we will be able to use our variable anywhere in our program, we can declare our variable anywhere in the program inside any function or in an inner block of code.

The below diagram shows how the static variable remains in the memory and avoids the condition of dangling pointers. Static variables with global scope

  1. A function() is called inside the main() function, memory is allocated by the system for the function() block.
  2. A global variable static temp is declared and initialized inside the function(). Let the address of temp is 2000. After returning the address of the temp function execution finishes, temp remains in the memory because of its static nature.
  3. Returned address 2000 is stored in ptr pointer and as temp is not deleted from the memory, ptr points to temp variable with value 10. So, ptr will not act as a dangling pointer.

Let us see what we can do in the Function Call example with static variables to avoid Dangling Pointers Problem in a C Program.

C Program :

OUTPUT :

Explanation :

  • notADanglingPointer() function now returns the address of a global variable.
  • ptr contains the address of temp variable i.e. a global variable.
  • ptr is acting as a Normal Pointer in this code.
  • Output will be value 10 i.e. stored in temp variable.

Now, Let us see how we can resolve the Dangling Pointer Problem in case variable goes out of scope.

  1. A pointer ptr is declared in the main() function, it is acting as a wild pointer.
  2. When we enter the inner block of code, ptr points to temp variable having value 10 with static keyword. temp has a global scope and will remain in the memory after the program control moves out of the inner block.
  3. ptr contains the address of temp. So, ptr will point to a global variable temp with value 10 and will not act as a dangling pointer.

Dangling Pointer Problem in case Variable goes out of scope

C Program :

OUTPUT :

Explanation :

  • First, the ptr is acting as a wild pointer.
  • We have an inner block of code, with a static integer variable temp. It has a global scope, so after the execution of the inner block it will not get destroyed and will remain until the execution of the program finishes.
  • ptr now contains the address of a static variable temp from the inner block of code.
  • As temp remains in the memory, ptr still points to the temp memory location. printf("%d", *ptr) will print 10 in the output console.

Conclusion

  • Dangling Pointers are created because of deallocation of memory blocks or when a variable goes out of scope.
  • Dangling Pointers can create an error in the execution of the program, and this error creates a Dangling Pointer Problem.
  • We can avoid such problems using techniques such as assigning NULL to the pointer as soon as the memory is deallocated and using static variables so that the variable remains in the memory until the execution of the program finishes.

See Also: