473,289 Members | 2,106 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,289 software developers and data experts.

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 2317


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.supernews.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*******@presby.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.supernews.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********@comcast.net> wrote in message news:M4********************@comcast.com...

"Alan" <al**@surfbest.net> wrote in message
news:10*************@news.supernews.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********@comcast.net> wrote in message news:M4********************@comcast.com...

"Alan" <al**@surfbest.net> wrote in message
news:10*************@news.supernews.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 << "constructor " << 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 << "constructor ?" << 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.supernews.com...

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

"Alan" <al**@surfbest.net> wrote in message
news:10*************@news.supernews.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 << "constructor " << 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 << "constructor ?" << 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********@hotmail.com> wrote in message news:41*********************@news.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********@hotmail.com> wrote in message news:41*********************@news.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
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
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. ...
6
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
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...
6
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...
3
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...
0
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...
10
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 ?...
14
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)...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...

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.