Join Regular Classroom : Visit ClassroomTech

Dangling / Wild pointers in C

When writing an application, developers typically include pointers to a variety of data objects. In some scenarios, the developer may accidentally use a pointer to an invalid or deallocated object, causing the application to enter an unintended execution flow. This usually causes the application to crash, but can result in far more dangerous behavior. This is the The most common bugs related to pointers and memory management known as dangling/wild pointers.

1. Dangling pointer occurs at the time of the object destruction when the object is deleted or de-allocated from memory without modifying the value of the pointer. In this case, the pointer is pointing to the memory, which is de-allocated.

Example

#include <stdio.h>  
int main() {  
	int *p=(int *)malloc(sizeof(int));   // it will create an array and return the base address of the array
	int a=210;  
	p=&a;      // assigining the variable with address of variable a
	free(p);  // releasing the memory
	return 0;  
}  

In above code the statement free(p) de-allocates the memory, and ‘p’ pointer becomes dangling as it is pointing to the de-allocated memory. If we assign the NULL value to the ‘p’, then ‘p’ will not point to the deleted memory. Therefore, we can say that p is not a dangling pointer.

2. A function returns a pointer to one of its local variables, and since this local variable is defined only for the function, the pointer becomes invalid once the function ends.

Example

#include <stdio.h>  
int *val() {
	int a=10;    //initializing the variable with a val
	return &a;  //return the address of the variable
}  
int main() {  
	int *ptr=val();  
	printf("%d", *ptr);  
	return 0;  
}  

Output:
Runtime Error (Segmentation fault)

Explanation:
First, we create the main() function in which we have declared ‘ptr’ pointer that contains the return value of the val(). When the val() is called, then the control moves to the context of the int *val(), the val() returns the address of the ‘a’ variable.

When control comes back to the context of the main() function, it means the variable ‘a’ is no longer available. Therefore, we can say that the ‘ptr’ pointer is a dangling pointer as it points to the de-allocated memory.


You Missed

Also Checkout