C Books Guide and List
C++ Books Guide and List
Best Java Books

3,749 questions

4,049 answers

114 comments

10,705 users

What is a dangling pointer?

0 votes
25 views
asked by smith Geek (15,340 points)

3 Answers

0 votes
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. Example: 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.
answered by rajesh Guru (39,140 points)
0 votes
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.
answered by smith Geek (15,340 points)
0 votes
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.
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.
answered by smith Geek (15,340 points)

Related questions

0 votes
1 answer 101 views
101 views asked by steve Sr Member (1,460 points)
0 votes
1 answer 43 views
43 views asked by steve Sr Member (1,460 points)
0 votes
1 answer 1,587 views
1,587 views asked by albertina Geek (15,670 points)
0 votes
1 answer 10 views
0 votes
1 answer 32 views
32 views asked by smith Geek (15,340 points)
...