473,663 Members | 2,738 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

delete does not work

Below is a simple code:

#include <iostream>

class base{
public:
base(): i(11){std::cout <<"base constructor"<<' \n';}
virtual void f() = 0;
virtual ~base(){ std::cout<<"bas e destructor"<<'\ n';}
int i;
};

class derv1 : public base{
public:
derv1(){std::co ut<<"derv1 constructor"<<' \n';}
void f(){}
~derv1(){std::c out<<"derv1 destructor"<<'\ n';}
};

class derv2 : public derv1{
public:
derv2(){i=22;st d::cout<<"derv2 constructor"<<' \n';}
~derv2(){std::c out<<"derv2 destructor"<<'\ n';}
};

int main(){
base *b1;
derv1 *d1;

derv2 *d2 = new derv2;

b1 = d2;
std::cout<<b1<< " "<<d2->i<<'\n';
delete b1; //LINE1

std::cout<<"aft er delete d1"<<'\n';
std::cout<<b1->i<<" "<<d2->i<<'\n'; //LINE2
}
I delete b1 at LINE1. Why LINE2 still output the correct result---22?

Thanks.

Jack

Jun 22 '06 #1
6 2022
* ju******@gmail. com:
int main(){
base *b1;
derv1 *d1;

derv2 *d2 = new derv2;

b1 = d2;
std::cout<<b1<< " "<<d2->i<<'\n';
delete b1; //LINE1

std::cout<<"aft er delete d1"<<'\n';
std::cout<<b1->i<<" "<<d2->i<<'\n'; //LINE2
}
I delete b1 at LINE1. Why LINE2 still output the correct result---22?


At that point any behavior whatsoever is correct, because the behavior
of accessing the object after destruction, is undefined.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jun 22 '06 #2
junw2000 wrote:
delete b1; //LINE1 std::cout<<b1->i<<" "<<d2->i<<'\n'; //LINE2
Please put spaces around operators, for readability.
I delete b1 at LINE1. Why LINE2 still output the correct result---22?


Because any use of b1 after the delete is undefined behavior. That means the
program could appear to work correctly, or the nearest toilet could explode,
or anything in between.

Tip: Learn all the ways to avoid undefined behavior (basically by avoiding
anything the slightest bit suspicious), and keep all your code within this
subset. For example, many folks use only smart-pointers, and if you can't,
at least do this:

delete b1;
b1 = NULL;

You can test b1 for NULL now, and if you slip up you will _probably_ get a
hard but reliable crash.

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!
Jun 22 '06 #3
Lav

ju******@gmail. com wrote:
Below is a simple code:

#include <iostream>

class base{
public:
base(): i(11){std::cout <<"base constructor"<<' \n';}
virtual void f() = 0;
virtual ~base(){ std::cout<<"bas e destructor"<<'\ n';}
int i;
};

class derv1 : public base{
public:
derv1(){std::co ut<<"derv1 constructor"<<' \n';}
void f(){}
~derv1(){std::c out<<"derv1 destructor"<<'\ n';}
};

class derv2 : public derv1{
public:
derv2(){i=22;st d::cout<<"derv2 constructor"<<' \n';}
~derv2(){std::c out<<"derv2 destructor"<<'\ n';}
};

int main(){
base *b1;
derv1 *d1;

derv2 *d2 = new derv2;

b1 = d2;
std::cout<<b1<< " "<<d2->i<<'\n';
delete b1; //LINE1

std::cout<<"aft er delete d1"<<'\n';
std::cout<<b1->i<<" "<<d2->i<<'\n'; //LINE2
}
I delete b1 at LINE1. Why LINE2 still output the correct result---22?

Thanks.

Jack


Hi Jack,

Better practice would be

delete b1;
b1 = NULL;

because you never know how delete 'ed variable are going to respond.

Thanks
Lav

Jun 22 '06 #4
Lav wrote:

Better practice would be

delete b1;
b1 = NULL;

because you never know how delete 'ed variable are going to respond.


You never know how null pointers are going to respond, either. In a code
snippet as short as the original there's no point in setting the pointer
to null. You know from inspection that it shouldn't be used after the
delete. There's no need to test it.

--

Pete Becker
Roundhouse Consulting, Ltd.
Jun 22 '06 #5
Lav wrote:
[snip]
Better practice would be

delete b1;
b1 = NULL;

because you never know how delete 'ed variable are going to respond.


While this won't *cause* problems (so far as I'm aware)
it won't catch plenty of common newbie problems.

I try to keep pointers as data members of a class.
I also try to keep it such that the pointer is assigned to
memory in an initiation step such as a ctor or a named
ctor, and deleted in the dtor. This way, my memory leaks
and wild pointers are as localized as I can make them,
and tend to be easier to find and easier to correct.

It's an extension of a principle that I illustrate as follows.
Whenever I put a { in code, I immediately put in the
corresponding } to balance it. Then I put in the stuff
that goes between. So too with new calls. Whenever
I put in a new, I immediately put in the delete that
goes with. Then I am careful to only refer to the mem
allocated while between those two. The easy way to
do that is to lean on the object ctor/dtor process.

Similarly with other resources like file streams, etc.
Socks

Jun 22 '06 #6

Puppet_Sock wrote:
Lav wrote:
[snip]
Better practice would be

delete b1;
b1 = NULL;

because you never know how delete 'ed variable are going to respond.
While this won't *cause* problems (so far as I'm aware)
it won't catch plenty of common newbie problems.


Name one problem that it won't catch that not setting to 0 does.
I try to keep pointers as data members of a class.
I also try to keep it such that the pointer is assigned to
memory in an initiation step such as a ctor or a named
ctor, and deleted in the dtor. This way, my memory leaks
and wild pointers are as localized as I can make them,
and tend to be easier to find and easier to correct.


It is much easier to tell that there is a problem when the pointer has
an obviously erroneous value, like 0, instead of a possibly valid one.
It is hard to figure out that the problem is caused by your object
having been deleted if it looks like a valid object. By setting to 0
you not only increase the likely hood of being able to check if the
pointer has been deleted before calling it, you also increase the
obviousness of the problem when you don't. It is also, though
undefined, much more likely to crash than do something completely
random as read/write to location 0 is always bad and outside your
memory space.

For example. Say you have the following code:

delete x;

When it runs you get an explosion. Why? You look at your ptr and it
has some random value...the object appears normal. Why did it blow up?
You trace back a few miles and end up in some OS specific event loop
and into no-man's land. There is no indication as to why you are
exploding, yet it does. Somewhere, in response to some previous event,
/something/ happened to some object related to that instruction...o r
maybe it suffered from a heap thrashing as described below...

What would happen if you had set that value to 0?

Imagine the following code in that scenario:

x->doY(); // doY() writes to a buffer inside an X.

What happens if that pointer was not set to 0? Half the time it
crashes and half the time you get odd heap corruptions and you crash in
totally unrelated areas of code; now you need special debugger tools
and libraries to track buffer overruns and heap corruptions when they
occur and not when their effect is felt...this can take hours, days,
weeks.... What if you had set that to 0? Well, in most systems, you
would crash immediately (except in cases like the OP when the class is
VERY trivial) and the fact that it was because the ptr is invalid would
be very obvious. You could then either fix the logic error that caused
you to do this on a deleted pointer, or if there is no logic problem
and you just need to make sure it never happens:

if (x) x->doY();

There are numerous cases when setting the pointer to 0 saves time by
making bugs more obvious, making intent and purpose clear, and removing
double deletions. There are a few situations in which it doesn't
matter. There is no situation in which it is better not to and there
is no way to track what is happening unless you do.

Jun 22 '06 #7

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

Similar topics

5
5235
by: | last post by:
Hi all, I've been using C++ for quite a while now and I've come to the point where I need to overload new and delete inorder to track memory and probably some profiling stuff too. I know that discussions of new and delete is a pretty damn involved process but I'll try to stick to the main information I'm looking for currently. I've searched around for about the last too weeks and have read up on new and overloading it to some extent but...
11
912
by: Jonan | last post by:
Hello, For several reasons I want to replace the built-in memory management with some custom built. The mem management itlsef is not subject to my question - it's ok to the point that I have nice and working allocation deallocation routines. However, I don't want to loose the nice extras of new operator, like - constructor calling, typecasting the result, keeping the array size, etc. For another bunch of reasons, outside this scope I...
5
8078
by: mkaushik | last post by:
Hi everyone, Im just starting out with C++, and am curious to know how "delete <pointer>", knows about the number of memory locations to free. I read somewhere that delete frees up space assigned to <pointerby "new". Does "new" create a list of pointer names and the size of the memory array they point to? I also read that some compilers may store the number of consec mem locations a pointer points to, just before the first data...
3
3805
by: Kevin M | last post by:
I have one table and have created a form from that table. Also, I have created a delete query. I want to but a button on the form which will delete all records from the table; however, I cannot get anything to work. I know this is probably simple for more experienced Access users. Any help would be greatly appreciated. Thanks Kevin
29
4222
by: Jon Slaughter | last post by:
Is it safe to remove elements from an array that foreach is working on? (normally this is not the case but not sure in php) If so is there an efficient way to handle it? (I could add the indexes to a temp array and delete afterwards if necessary but since I'm actually working in a nested situation this could get a little messy. I guess I could set there values to null and remove them afterwards? Thanks, Jon
10
2085
by: jeffjohnson_alpha | last post by:
We all know that a new-expression, foo* a = new foo() ; allocates memory for a single foo then calls foo::foo(). And we know that void* p = ::operator new(sizeof(foo)) ; allocates a sizeof(foo)-sized buffer but does NOT call foo::foo().
15
5013
by: LuB | last post by:
I am constantly creating and destroying a singular object used within a class I wrote. To save a bit of time, I am considering using 'placement new'. I guess we could also debate this decision - but for the sake of this post ... I'm searching for an answer that assumes said decision. If I allocate memory in the class declaration: char buffer;
12
2558
by: Premal | last post by:
Hi, I tried to make delete operator private for my class. Strangely it is giving me error if I compile that code in VC++.NET. But it compiles successfully on VC++6.o. Can anybody give me inputs about it. I wanted that on my class delete should not work. Object pointer should be deleted using my function only which is taking care of reference count for particular class. Thanx in advance for your inputs.
23
1936
by: Martin T. | last post by:
Hi all! char* p = new char; // POD! .... delete p; // std compliant delete p; // will work on VC8 free(p); // will also work on VC8 I am interested on which platforms/compilers the second two statements
19
10744
by: Daniel Pitts | last post by:
I have std::vector<Base *bases; I'd like to do something like: std::for_each(bases.begin(), bases.end(), operator delete); Is it possible without writing an adapter? Is there a better way? Is there an existing adapter? Thanks, Daniel.
0
8345
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8548
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
8634
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5657
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
4182
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4349
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2763
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2000
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1757
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.