Generally, daggling 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.
For example,
#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 the allocated memory
free(piData);
//piData is dangling pointer
*piData = 10;
printf("%d",*piData);
return 0;
}
OutPut: Undefined Result
In simple words, we can say that a dangling pointer is a pointer that is not pointing to valid memory. So if we access these pointers then the behaviour of the program will undefine.
Answer:
Generally, daggling 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.
For example,
OutPut: Undefined Result
In simple words, we can say that a dangling pointer is a pointer that is not pointing to valid memory. So if we access these pointers then the behaviour of the program will undefine.
need an explanation for this answer? contact us directly to get an explanation for this answer