Home » Ask & Discuss » Board Exams - CBSE, ICSE, State Boards » Computer Science « Back to Discussion
Computer Science
Comments (4)
A dangling pointer is a cause a many problem in C language specially segmentation fault error. Ex:
int* p;
{
int q;
p=&q;
}
/* in this place you cannot access c as now the memory space containing the value of c is now no longer in use but p still points to the same place and so we say that p is a dangling pointer.That is p is pointing to a place which has been reallocated for some other purposes.*/
Another example which i can think of is :
int *p,*q;
p=(int*)malloc(sizeof(int));
q=p; /*p and q points to the same chunk of memory*/
free(p);/* now we free p so p points to NULL but q points to the same place so q is a dangling pointer*/
In Language like Java there is the concept of garbage collection etc. which tackles this if you are a C learner than always free memory after use.
hello dear
A dangling pointer arises when you use the address of an object after its lifetime is over. This may occur in situations like returning addresses of the automatic variables from a function or using the address of the memory block after it is freed. The following code snippet shows this:
class Sample
{
public:
int *ptr;
Sample(int i)
{
ptr = new int(i);
}
~Sample()
{
delete ptr;
}
void PrintVal()
{
cout << ?The value is ? << *ptr;
}
};
void SomeFunc(Sample x)
{
cout << ?Say i am in someFunc ? << endl;
}
int main()
{
Sample s1 = 10;
SomeFunc(s1);
s1.PrintVal();
}
In the above example when PrintVal() function is called it is called by the pointer that has been freed by the destructor in SomeFunc.













Dangling pointers are pointers that do not point to a valid object of the appropriate type. Dangling pointers arise when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory.