Developer community
0 votes
35 views
asked by Geek (15.3k points) 17 40 60 | 35 views

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 Guru (39.1k points) 10 22 34
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 Geek (15.3k points) 17 40 60
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 Geek (15.3k points) 17 40 60

Related questions

0 votes
1 answer
asked by steve Sr Member (1.5k points) 8 23 36 | 102 views
0 votes
1 answer
asked by steve Sr Member (1.5k points) 8 23 36 | 49 views
0 votes
1 answer
asked by albertina Geek (15.7k points) 5 9 21 | 1.6k views
0 votes
1 answer
asked by smith Geek (15.3k points) 17 40 60 | 14 views
0 votes
1 answer
asked by smith Geek (15.3k points) 17 40 60 | 36 views
Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

Categories


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

3.8k questions

4k answers

117 comments

10.7k users

3,751 questions
4,046 answers
117 comments
10,709 users