Generally, dangling pointers arise when the referencing object is deleted or deallocated, without changing the value of the pointers. It creates the problem because the pointer is still pointing the memory that is not available. When the user tries to dereference the daggling pointers than it shows the undefined behavior and can be the cause of the segmentation fault.
In simple words, we can say that dangling pointer is a pointer that not pointing a valid object of the appropriate type and it can be the cause of the undefined behavior.
Let’s see the below image for a better understanding.
In the image Pointer1 and Pointer2 is pointing to a valid object but Pointer3 is pointing an object that has been already deallocated. So Pointer3 becomes a dangling pointer when you will try to access the Pointer3 than you will get the undefined result or segmentation fault.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *piData = NULL;
//creating integer of size 10.
piData = malloc(sizeof(int)* 10);
//make sure piBuffer is valid or not
if (piData == NULL)
{
// allocation failed, exit from the program
fprintf(stderr, "Out of memory!\n");
exit(1);
}
free(piData); //free the allocated memory
*piData = 10; //piData is dangling pointer
printf("%d\n",*piData);
return 0;
}
Answer:
Generally, dangling pointers arise when the referencing object is deleted or deallocated, without changing the value of the pointers. It creates the problem because the pointer is still pointing the memory that is not available. When the user tries to dereference the daggling pointers than it shows the undefined behavior and can be the cause of the segmentation fault.
In simple words, we can say that dangling pointer is a pointer that not pointing a valid object of the appropriate type and it can be the cause of the undefined behavior.
Let’s see the below image for a better understanding.
In the image Pointer1 and Pointer2 is pointing to a valid object but Pointer3 is pointing an object that has been already deallocated. So Pointer3 becomes a dangling pointer when you will try to access the Pointer3 than you will get the undefined result or segmentation fault.
Output: undefined.
need an explanation for this answer? contact us directly to get an explanation for this answer