473,659 Members | 2,680 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reusing a deleted pointer.

Using VC++ (1998) compiler with PFE32 editor in Win2K Pro SP4.
(DigitalMars CD on order. )

The program (below) instantiates a class and then deletes it.
I would have thought that reusing the deleted pointer would
have caused an exception, but it does not - or my coding or
thinking is incorrect?

#include <iostream>
using namespace std;

class A {
int a;
public:
A(): a(0) { cout << " A::A()" << endl; }
~A() { cout << "~A::A()" << endl << endl; }
void print() { cout << "a = " << a << endl; }
void set(const int& aa) { a=aa; print(); }
};

int main() {

A* b = new A; // ptr
A& c = *b; // ref

b->set(10); // test ptr
c.set(5); // test ref

delete b;

try {
A& y = *b; // no problems!
y.set(55); // causes system error (msg in Dos-box)
} catch(...) { cout << "failed" << endl; exit(-1); }

cout << "No failure" << endl; // always gets here

return 0;
}


Jul 22 '05 #1
9 2347


Alan wrote:
Using VC++ (1998) compiler with PFE32 editor in Win2K Pro SP4.
(DigitalMars CD on order. )

The program (below) instantiates a class and then deletes it.
I would have thought that reusing the deleted pointer would
have caused an exception, but it does not - or my coding or
thinking is incorrect?


reusing a deleted pointer (or really any invalid pointer) simply causes
'undefined behavior'. Now undefined behaviour 'could' result in an
exception, the same way it 'could' result in your computer taking a trip
to mars... but neither is really necessary and if it seems to work ok
that could be attributed to undefined behavior as well.

David
Jul 22 '05 #2
In article <10************ *@news.supernew s.com>,
Alan <al**@surfbest. net> wrote:

The program (below) instantiates a class and then deletes it.
I would have thought that reusing the deleted pointer would
have caused an exception, but it does not - or my coding or
thinking is incorrect?


Deleting a pointer simply tells the operating system that it is free to
allocate the memory that it points to, for something else, whenever the OS
feels it is necessary. It does not actually clear that memory, or change
the pointer itself, because that would be a waste of CPU cycles in many
situations.

Therefore there is a good chance that you will actually be able to follow
that pointer to whatever it originally pointed to, for some time
thereafter... but you can't predict how long this will work.

--
Jon Bell <jt*******@pres by.edu> Presbyterian College
Dept. of Physics and Computer Science Clinton, South Carolina USA
Jul 22 '05 #3

"Alan" <al**@surfbest. net> wrote in message
news:10******** *****@news.supe rnews.com...
Using VC++ (1998) compiler with PFE32 editor in Win2K Pro SP4.
(DigitalMars CD on order. )

The program (below) instantiates a class and then deletes it.
I would have thought that reusing the deleted pointer would
have caused an exception, but it does not - or my coding or
thinking is incorrect?

#include <iostream>
using namespace std;

class A {
int a;
public:
A(): a(0) { cout << " A::A()" << endl; }
~A() { cout << "~A::A()" << endl << endl; }
void print() { cout << "a = " << a << endl; }
void set(const int& aa) { a=aa; print(); }
};

int main() {

A* b = new A; // ptr
A& c = *b; // ref

b->set(10); // test ptr
c.set(5); // test ref

delete b;

try {
A& y = *b; // no problems!
y.set(55); // causes system error (msg in Dos-box)
} catch(...) { cout << "failed" << endl; exit(-1); }

cout << "No failure" << endl; // always gets here

return 0;
}


To follow up on the other replies, if you look more carefully at the
contents of the object "b" you
will see ( at least on VC++6) that after deletion, the memory used by b is
written over and the original
value a is destroyed! I tinkered a bit with this program, if you do a few
more allocations of A's, you
will eventually find that an object is allocated at the same address as b,
very nasty, now modifying b modifies
some other unrelated object! . Just goes to show, just because you don't
crash, all may not be well.

By the way, your object is too simple to cause a crash, the original
address of b would almost always point to to valid memory so deferencing it
would not cause a crash after
you delete it - just put some virtual functions in your class and try
calling one of those after deletion and then
you'll crash for sure..!

dave

Jul 22 '05 #4

"Dave Townsend" <da********@com cast.net> wrote in message news:M4******** ************@co mcast.com...

"Alan" <al**@surfbest. net> wrote in message
news:10******** *****@news.supe rnews.com... [snip]
To follow up on the other replies, if you look more carefully at the
contents of the object "b" you
will see ( at least on VC++6) that after deletion, the memory used by b is
written over and the original
value a is destroyed! I tinkered a bit with this program, if you do a few
more allocations of A's, you
will eventually find that an object is allocated at the same address as b,
very nasty, now modifying b modifies
some other unrelated object! . Just goes to show, just because you don't
crash, all may not be well.

By the way, your object is too simple to cause a crash, the original
address of b would almost always point to to valid memory so deferencing it
would not cause a crash after
you delete it - just put some virtual functions in your class and try
calling one of those after deletion and then
you'll crash for sure..!

dave


Thanks Dave, John and David.
Jul 22 '05 #5

"Dave Townsend" <da********@com cast.net> wrote in message news:M4******** ************@co mcast.com...

"Alan" <al**@surfbest. net> wrote in message
news:10******** *****@news.supe rnews.com... [snip] To follow up on the other replies, if you look more carefully at the
contents of the object "b" you
will see ( at least on VC++6) that after deletion, the memory used by b is
written over and the original
value a is destroyed! I tinkered a bit with this program, if you do a few
more allocations of A's, you
will eventually find that an object is allocated at the same address as b,
very nasty, now modifying b modifies
some other unrelated object! . Just goes to show, just because you don't
crash, all may not be well.

By the way, your object is too simple to cause a crash, the original
address of b would almost always point to to valid memory so deferencing it
would not cause a crash after
you delete it - just put some virtual functions in your class and try
calling one of those after deletion and then
you'll crash for sure..!

dave


I've put a virtual function in but it didn't fail until I introduced a static
variable into the class for instance counting. I've cut and cut the
original program.. The code below (I'm using VC++6 too) succeeds
or fails, per user choice. What puzzles me is why one class fails and
the other doesn't - as the differences appear small.

#include <iostream>
using namespace std;

class Failure {
int a;
static int count; // count instances, display them
public:
Failure(): a(0) { cout << "constructo r " << count++ << endl; }
~Failure() { cout << "destructor " << --count << endl; }
virtual void set(const int& aa) { a=aa; }
};

class Success {
int a;
static int count; // count instances, no display
public:
Success(): a(0) { count++; cout << "constructo r ?" << endl; }
~Success() { --count; cout << "destructor ?" << endl; }
virtual void set(const int& aa) { a=aa; }
};

int Failure::count = 1;
int Success::count = 1;

int main(int argc) {

// no command line arguments (succeeds)
if( argc == 1 )

Success* s = new Success;
delete s;
cout << "class Success *s: try { s->set(1000) }" << endl;
try {
s->set(1000);
} catch(...) { cout << "try failed" << endl; exit(-1); }
}

// one or more command line arguments (fails)
else {
Failure* f = new Failure;
delete f;
cout << "class Failure *f: try { f->set(1000) }" << endl;
try {
f->set(1000);
} catch(...) { cout << "try failed" << endl; exit(-1); }
}

cout << "No failure" << endl;
return 0;
}

Regards,
Alan


Jul 22 '05 #6

"Alan" <al**@surfbest. net> wrote in message news:10******** *****@news.supe rnews.com...

"Dave Townsend" <da********@com cast.net> wrote in message news:M4******** ************@co mcast.com...

"Alan" <al**@surfbest. net> wrote in message
news:10******** *****@news.supe rnews.com...

[snip]
To follow up on the other replies, if you look more carefully at the
contents of the object "b" you
will see ( at least on VC++6) that after deletion, the memory used by b is
written over and the original
value a is destroyed! I tinkered a bit with this program, if you do a few
more allocations of A's, you
will eventually find that an object is allocated at the same address as b,
very nasty, now modifying b modifies
some other unrelated object! . Just goes to show, just because you don't
crash, all may not be well.

By the way, your object is too simple to cause a crash, the original
address of b would almost always point to to valid memory so deferencing it
would not cause a crash after
you delete it - just put some virtual functions in your class and try
calling one of those after deletion and then
you'll crash for sure..!

dave


I've put a virtual function in but it didn't fail until I introduced a static
variable into the class for instance counting. I've cut and cut the
original program.. The code below (I'm using VC++6 too) succeeds
or fails, per user choice. What puzzles me is why one class fails and
the other doesn't - as the differences appear small.

#include <iostream>
using namespace std;

class Failure {
int a;
static int count; // count instances, display them
public:
Failure(): a(0) { cout << "constructo r " << count++ << endl; }
~Failure() { cout << "destructor " << --count << endl; }
virtual void set(const int& aa) { a=aa; }
};

class Success {
int a;
static int count; // count instances, no display
public:
Success(): a(0) { count++; cout << "constructo r ?" << endl; }
~Success() { --count; cout << "destructor ?" << endl; }
virtual void set(const int& aa) { a=aa; }
};

int Failure::count = 1;
int Success::count = 1;

int main(int argc) {

// no command line arguments (succeeds)
if( argc == 1 )

Success* s = new Success;
delete s;
cout << "class Success *s: try { s->set(1000) }" << endl;
try {
s->set(1000);
} catch(...) { cout << "try failed" << endl; exit(-1); }
}

// one or more command line arguments (fails)
else {
Failure* f = new Failure;
delete f;
cout << "class Failure *f: try { f->set(1000) }" << endl;
try {
f->set(1000);
} catch(...) { cout << "try failed" << endl; exit(-1); }
}

cout << "No failure" << endl;
return 0;
}

Regards,
Alan


There is an opening brace missing after "if( argc == 1 )",
should read "if(argc == 1) {"
I can't explain it - it is there in the original file ;-)
Jul 22 '05 #7
Alan wrote:
I've put a virtual function in but it didn't fail until I introduced a static variable into the class for instance counting. I've cut and cut the
original program.. The code below (I'm using VC++6 too) succeeds
or fails, per user choice. What puzzles me is why one class fails and
the other doesn't - as the differences appear small.


That's the nature of undefined behaviour. Understanding why it has a
certain effect often requires intimite knowledge of the compiler and its
optimizations. The policy is to *never* write any code that has
undefined behaviour, since even if such code appears to work here and
now, as soon as you demo the system to an investor, it will almost
certainly crash.

Tom
Jul 22 '05 #8

"Tom Widmer" <to********@hot mail.com> wrote in message news:41******** *************@n ews.easynet.co. uk...
Alan wrote:
> I've put a virtual function in but it didn't fail until I introduced

a static
variable into the class for instance counting. I've cut and cut the
original program.. The code below (I'm using VC++6 too) succeeds
or fails, per user choice. What puzzles me is why one class fails and
the other doesn't - as the differences appear small.


That's the nature of undefined behaviour. Understanding why it has a
certain effect often requires intimite knowledge of the compiler and its
optimizations. The policy is to *never* write any code that has
undefined behaviour, since even if such code appears to work here and
now, as soon as you demo the system to an investor, it will almost
certainly crash.


If you could give me an example of the try..catch sequence (where the
'try' fails and the 'catch' catches it) in code that has no undefined
behaviour - it would be most helpful.

tia
sincerely,
-Alan
Jul 22 '05 #9
Alan wrote:
"Tom Widmer" <to********@hot mail.com> wrote in message news:41******** *************@n ews.easynet.co. uk...
Alan wrote:
> I've put a virtual function in but it didn't fail until I introduced

a static
variable into the class for instance counting. I've cut and cut the
original program.. The code below (I'm using VC++6 too) succeeds
or fails, per user choice. What puzzles me is why one class fails and
the other doesn't - as the differences appear small.


That's the nature of undefined behaviour. Understanding why it has a
certain effect often requires intimite knowledge of the compiler and its
optimizations . The policy is to *never* write any code that has
undefined behaviour, since even if such code appears to work here and
now, as soon as you demo the system to an investor, it will almost
certainly crash.

If you could give me an example of the try..catch sequence (where the
'try' fails and the 'catch' catches it) in code that has no undefined
behaviour - it would be most helpful.


Try-catch blocks are used with throw. If nothing throws, a try-catch is
useless.

int main()
{
try
{
throw 2;
}
catch (int i)
{
std::cout << i << " was catched.";
}
}

But I fail to see the point of your question. Using invalid pointers
don't throw exceptions, it breaks your program.
Jonathan
Jul 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
13212
by: Robin Forster | last post by:
I have two classes: aule_gl_window (parent class) and aule_button (sub class) I want to call the super class (parent) constructor code from the sub class constructor.
5
3628
by: Boogie El Aceitoso | last post by:
Hi, The code below produces an access violation error, complaining that an object is destroyed twice. I don't understand why this happens. Any help would be appreciated. --------main.cpp--------------------------------------------------------------------------- #include "AbstractActivator.h"
6
2607
by: Gil | last post by:
Hi, I created an object set private variables in the object. I want to reuse the object but with default values. How can I do this? SomeObject so1; so1.setValue1(1); so1.setValue2(1);
2
1153
by: Till Crueger | last post by:
Hi, I was wondering about a problem, that might occur when you delete a class in a method which was called by the deleted class. This is not actually a problem I ran accross (I would probably restructure if possible). It is rather one of those "What if" Questions. Here is some code to explain what I mean: class B;
6
2871
by: B. Penn | last post by:
Hi, I was testing pointers and found that I could still dereference a pointer and access the value/variable it pointed to after deleting it, which confused me for "the variable it pointed to is deleted and it now points to nowhere". Did I do anything wrong? I checked a couple of references but couldn't explain it. Could anyone kindly clear it for me please? Here is my code, which compiled with both GNU C++ and Visual Studio ..Net:
3
2528
by: Ganesh | last post by:
On devx site, I saw following code. It says when a derived class is tried to cast to base type, it looks at the missing vtable and complains if the object is already deleted. I am of the opinion that this doesnt work if the destructor is not virtual or when the class has no virtual members. I would like to know is there anything wrong in what I am thinking. (I agree it is better to keep base class dtor as virtual, but supposing it is not...
0
1127
by: techie | last post by:
Hi, I've created a COM object in VC++ that I call from XMetal. I pass the COM object (via a XMetal macro) my XMetal Application object by a put_ method. In my put_ method I call QueryInterface for the _Application interface and create an instance of a class called CXMetalApp: STDMETHODIMP CXMLEditorInterface::put_Application(LPDISPATCH newVal) { AFX_MANAGE_STATE(AfxGetStaticModuleState())
10
1115
by: ac.c.2k7 | last post by:
Hello Everyone, The solution to this is to copy the data from the next node into this node and delete the next node!. 1. But if the node to be deleted is the last node. Then what should we do ? 2. If the list is Head node? 3 If the list is circular then what all conditions we need to check? Thanks,
14
17135
by: Mark | last post by:
Hi, I would like to check if my object has been deleted or not, but my program keeps crashing. Here's the simplified code (in infinite loop) delete tetromino; //if(tetromino==NULL) tetromino = new TetrominoI; This continuously replaces the tetromino as expected, but if I take
0
8427
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8746
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8525
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7356
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4335
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1975
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1737
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.