top

Search

C Tutorial

.

UpGrad

C Tutorial

Dangling Pointer in C

Overview

Dangling pointers refer to the pointers that point to a deallocated memory block. The corresponding condition produces an error called Dangling Pointer Problem. Typically, a dangling pointer comes into the picture when a pointer pointing towards a variable goes out of scope or when a variable’s/object’s memory gets deallocated.

The occurrence of dangling pointers can result in some unforeseen errors during the implementation of a program. Hence, you must avoid them when writing a program.

What is a Dangling Pointer in C?

A dangling pointer in C indicates a pointer pointing to some deleted/freed location from the program's memory. Here the program’s memory refers to the memory that is presently not in the use of the program.

When it comes to dynamic memory allocation, we use calloc(), malloc() functions to allocate a memory block. Moreover, we use the free() function to deallocate a memory block. A dangling pointer is generated after you deallocate a memory block by utilising the free() function.

How does a Dangling Pointer in C work?

A dangling pointer in C is generated when we don’t alter the value of a pointer when a variable goes out of scope or after the deallocation of a memory block.

Let’s understand how a dangling pointer works with the help of the below diagram. As seen from the diagram, the memory taken up by the integer variable is deallocated. The pointer ‘ptr’ that points to the deallocated memory now works as a dangling pointer.

The ‘ptr’ is an integer pointer that points to an integer variable with the value 100. It holds the address to the variable. When an integer variable is deallocated from memory, ptr transfers from being a usual pointer to a dangling pointer. Subsequently, it points to some false/not-in-use locations.

Different Techniques Where Pointers React as Dangling Pointers in C

There are three ways in which a pointer can work as a dangling pointer in C. 

i. Deallocation of memory

ii. Function Call

iii. Variable goes out of scope

Let’s check out the details of each method.

i. Deallocation of memory

The library functions assist in allocating and deallocating memory blocks. The malloc() and calloc() functions are utilised to allocate a memory block, whereas the free() function is used in deallocating a memory block. If you deallocate a memory block through the free() function but don’t alter the value of the pointer, it will result in a dangling pointer. Note that the free() function accepts a single parameter, i.e. a pointer points towards the memory to get deallocated.

Here’s a dangling pointer in C with example that demonstrates the deallocation of memory using the free() function.

// Program that demonstrates dangling pointers using dynamic memory allocation concept

#include <stdio.h>
#include <stdlib.h>
 
int main() 
{
// The malloc() function allocates 4 bytes of int memory block during runtime
int *ptr = (int *)malloc(sizeof(int)); // regular pointer
 
*ptr = 15;
 
// The following is the memory block deallocated through free() function
free(ptr);
 
 
// Now ptr works as a dangling pointer
printf("%d", *ptr); // It prints garbage value in the output console
 
return 0;
}

The given program uses malloc() to allocate memory for an integer pointer ptr, which is then assigned the value 15. Later, the free() function is used to deallocate the memory block pointed to by ptr, making it a dangling pointer. Accessing the value pointed to by ptr using *ptr in the printf() statement results in undefined behaviour.

ii. Function Call

As you declare a variable within a function, it works as a local variable because it can’t be accessed outside the function’s scope.

Suppose the main() function's pointer holds the address to the particular local variable within the function. Consequently, you can access that local variable’s address until the function’s implementation continues. Once the function execution stops, all internal variables move to garbage collection. They will not exist in memory anymore.

However, the pointer of the main() function still points to that particular address currently not present in memory. So, this scenario creates a dangling condition, and the generated pointer is called a dangling pointer.

Here’s an example program demonstrating dangling pointer in C program using a function call.

#include <stdio.h>
 
// defining danglingPointer() function
int *danglingPointer() 
{
//The 'var' variable has local scope
int var = 5;
 
// returns address of var variable
return &var;
}
 
int main() 
{
// ptr will point to a garbage value because var variable will not exist after the execution of the below command
int *ptr = danglingPointer();
 
// Now ptr is a dangling pointer and contains some random address. It now points to a garbage value
printf("%d", *ptr);
 
return 0;
}

 Output:

Segmentation fault

 In the above dangling pointer example, an integer pointer ‘ptr’ is assigned a function call from the danglingPointer() function. This function’s return type is int *. It means that the function will return an address of an integer block which can be stored in an integer pointer.

The danglingPointer() function contains an integer variable var with local scope, and we assigned the value 15 to it. After returning the var variable and the address, the memory being occupied by the danglingPointer() function will be deallocated.

The main() function contains an address saved in the ptr pointer. It points to some deallocated memory which was earlier occupied by var variable. Now ptr works as a dangling pointer since it points to the deallocated memory block.

The output we get is a segmentation fault. This is because the program attempts to access a part of memory that it is not permitted to access. 

iii. Variable goes out of scope

A variable declared within an inner block of code has a local scope, which gets destroyed when the execution within the inner block terminates. If we assign a local variable’ address to a pointer which is declared outside of the scope, then it will work as a dangling pointer outside the code block. 

Here’s a program that demonstrates using a dangling pointer where a variable goes out of scope.

#include <stdio.h>
 
int main()  
{
 int var = 5;
// A pointer that has not been initialized is
// known as a Wild Pointer, ptr is a Wild Pointer.
int *ptr;
 
// variables declared inside the block will get destroyed at the end of the execution of this block
{
    ptr = &var; // acting as normal pointer
}
 
// var is now removed from the memory (out of scope)
//Now ptr is a dangling pointer
printf("%d %d", *ptr, var);
 
// as var is not in the memory anymore so it can't be modified using ptr
 
// prints garbage value
printf("%d", *ptr);
 
 
return 0;
}

 Output:

/tmp/eCpRzkbqQD.o
5 55

Firstly, we declare an integer pointer ‘ptr’ without the initialisation. It is considered a Wild Pointer. The program then defines an integer variable ‘var’ whose scope is until the block’s execution ends. The var’s address is assigned to the ptr pointer.

Suppose the base address is 500, at which the var is allocated. When this block’s scope ends, ptr stays unaffected since it is declared in the external code block. The memory occupied by var is deallocated as it is declared within the block.

Now ptr still holds the address 500. However, nothing exists at this location. It leads to a dangling pointer. The var variable doesn’t exist in the memory, so you can’t alter its value using the ptr pointer.

 Avoiding Errors Faced in Dangling Pointer in C

Along with understanding how a dangling pointer works, you must also understand how to avoid dangling pointer in C. You can avoid it either by using static variables (if variables have a local scope) or assigning NULL to the pointer (in case of memory deallocation).

Let’s look at the details of methods to avoid this error. 

i. Assign NULL after the deallocation of memory

You must assign NULL to the pointer ptr once the memory block pointed by ptr is deallocated by leveraging the free() function. 

ii. Static variables with global scope

Static variables refer to the variables existing in the memory until the program execution continues. You can use the static keyword to declare a static variable which will avoid dangling pointer problems.

Note: You can avoid dangling pointer errors in C by ensuring that the pointer is properly initialised before it is dereferenced. 

Conclusion

Dangling pointer in C is helpful when the programmer fails to initialise the pointer with a valid address. Appropriately initialising the pointer will minimise the occurrence of dangling pointers.

Understanding as well as implementing the concept of dangling pointer in C is essential to realise its significance in different scenarios. Following the approach discussed above helps you to curtail the dangling pointer problem.

Along with grasping the fundamentals of C through tutorials, pursuing upGrad’s Executive Post Graduate Programme in Software Development by IIIT-B can prove to be a wise decision for your career advancement! The program imparts you with fundamentals of computer science, the process of building interactive web UI, software development processes, and more, enabling you to bag attractive industry opportunities.

Enroll now to commence your journey! 

FAQs

Q. Is null a dangling pointer?

No, a pointer can’t be dangling and null simultaneously. A null pointer doesn’t point to any memory location, whereas a dangling pointer points to a memory location that has been deallocated.

Q. How do dangling pointers show unpredictable behaviour?

Dangling pointers generate during object destruction, whenever an object which has an incoming reference is deallocated or deleted without altering the value of the pointer. The system might reallocate the earlier freed memory. So, the dangling pointer will show unpredictable behaviour because the memory may now have entirely different data.

Q. What are the differences between a dangling pointer and a void pointer?

A dangling pointer points to a memory location that has been freed or deleted. A void pointer is a specific pointer that points to some data location in storage that doesn’t have any particular type. A dangling pointer points to the deleted object, whereas a void pointer can be assigned the address irrespective of data type.

Q. How do dangling pointers become security holes?

Dangling pointer bugs often become security holes. For instance, if the pointer is utilized to create a virtual function call, a different address may be called because the vtable pointer is overwritten.

Leave a Reply

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