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 Jan 1, 2014 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 Jan 1, 2014 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 Jan 11, 2014 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 Jan 11, 2014 by smith Geek (15,340 points)

Related questions

0 votes
1 answer 100 views
100 views asked Jul 11, 2011 by steve Sr Member (1,460 points)
0 votes
1 answer 42 views
42 views asked Jul 11, 2011 by steve Sr Member (1,460 points)
0 votes
1 answer 1,579 views
1,579 views asked May 27, 2011 by albertina Geek (15,670 points)
0 votes
1 answer 9 views
9 views asked Jan 1, 2014 by smith Geek (15,340 points)
0 votes
1 answer 31 views
31 views asked Jan 1, 2014 by smith Geek (15,340 points)
...