After this code executes

ptr = new myStuff;
// some code ...
delete ptr;

the memory allocated is freed but ptr still contains the mem addr of the 1st byte of the previously allocated mem. Is there some history to this? Why didn't the C++ standard also have the delete operator reset ptr to NULL? Is there some clever coding which makes use of ptr still pointing to the freed mem?

Yeah, I think the clever code is called a runtime error. I'm no expert though.

Usually people that code in C++ don't want things done for them that they don't have control over. If you really want something that nulls and deletes a pointer, write it yourself.

As for a reason, this is a bit contrived but...what if you where writing an operating system that runs a thread to delete junk pointers (like the garbage collector in .NET). Now what if you wanted to keep a list of these pointers to send to a different thread at a certain interval to indicate memory that is now usable? I suppose you could create the list before the pointer is deleted, but then you are just taking up extra memory!

After deleting you could simply set your pointer manually to NULL:

int *ptr = new int;
delete ptr;
ptr = 0;

By the way, why should delete reset the pointer to NULL , C++ is a programmer's language and those programmers want to control every single aspect of the language, this brings with it that you'll have to do some things manually, but in this case, it's only one single line of code extra :) ...

>>Why didn't the C++ standard also have the delete operator reset ptr to NULL?
First of all you are simply **NO ONE** to ask question like this. C++ standards have been made by the most proficient and experienced programmers of this language. If you think there should be a feature added doesn't means it should be added. A boon to you may be disaster to others. C++ standards have to keeps everyone in mind.

If you really feel that everyone is dumb and delete should really reset the pointer to null answer this:
Lets say I have the following code. Just check what would happened if delete would reset the pointer to zero:

int * p=new int;
int *q=p;// q points to same memory as p
delete p; //deleting p and setting it to zero
delete q;// Shit ! deleting pointer to null 0

Got that!!
So before opening the mouth and say "Mommy I want this candy" try to think how costly( or perhaps dangerous) that candy would be. Even if you can't think how costly it is, just trust your mother that she did a good thing by not buying you that candy.

commented: A little harsh don't you think? And deleting a null pointer is allowed. And your code does not prove any point. -1

Yeah, if you really want a feature like that you might have to implement it yourself: Create a new pointer datatype and overload the delete operator for it in such a way that the pointer is always set to NULL after releasing the allocated memory :) ...

Yeah, if you really want a feature like that you might have to implement it yourself: Create a new pointer datatype and overload the delete operator for it in such a way that the pointer is always set to NULL after releasing the allocated memory :) ...

If really wanted to things like this, I would simply create a (templatized) function like this

template<class T> 
inline void destroy(T*& p) 
{ 
    delete p; 
    p = 0; 
}

But the fact remains that these things( my function hack or your overloaded pointer hack or any other such things) will lead to error like I pointed.
Also note what happens when I use this destroy function like this:

int* f();//some function returning a pointer.
	int* p;//some pointer pointing to some memory.
	// ...
	destroy(f());	// error: trying to pass an rvalue by non-const reference
	destroy(p+1);	// error: trying to pass an rvalue by non-const reference

>>Why didn't the C++ standard also have the delete operator reset ptr to NULL?
First of all you are simply **NO ONE** to ask question like this. C++ standards have been made by the most proficient and experienced programmers of this language. If you think there should be a feature added doesn't means it should be added. A boon to you may be disaster to others. C++ standards have to keeps everyone in mind.

If you really feel that everyone is dumb and delete should really reset the pointer to null answer this:
Lets say I have the following code. Just check what would happened if delete would reset the pointer to zero:

int * p=new int;
int *q=p;// q points to same memory as p
delete p; //deleting p and setting it to zero
delete q;// Shit ! deleting pointer to null 0

Got that!!
So before opening the mouth and say "Mommy I want this candy" try to think how costly( or perhaps dangerous) that candy would be. Even if you can't think how costly it is, just trust your mother that she did a good thing by not buying you that candy.

Seems a bit hard on the OP. He/she was just asking to be educated. Is that a problem?
As for your code, I hope the OP does get it, but I'm afraid I don't.
Calling delete on p deallocates it and, at the request of the OP, sets P to NULL. How does that affect q? q still contains a pointer to the memory which has been deallocated. Calling delete q after delete p is always doomed to failure whether p was cleared or not.
Not trying to be difficult. I genuinely don't see what you're trying to illustrate here.
Please educate me - but be nice eh... :S

sid> Just check what would happened if delete would reset the pointer to zero:

Nothing would happen! Are you a mindless idiot? Did your brain fall out? Did you replace it with a turd you found on the ground? delete does nothing if it's passed a zero pointer! Moron!

I mean, how stupid would you have to be to think that the OP's question was about the designers of C++ being idiots? Answer: a complete and total moron, i.e., siddhantes!!! The OP's question was about the REASONING (something sid cannot comprehend) of the designers.

To the OP: Don't worry about the "sidiot," as we shall call him. He has serious personality problems. Just ignore anything he says. Everybody else does!

(P.S. The tone of the above is entirely contingent on the sidiot's original tone.)

commented: Ha! Got the tone just right! +1

>>Seems a bit hard on the OP. He/she was just asking to be educated. Is that a problem?
Not at all. I have done my job.

>>
As for your code, I hope the OP does get it, but I'm afraid I don't.
Calling delete on p deallocates it and, at the request of the OP, sets P to NULL. How does that affect q? q still contains a pointer to the memory which has been deallocated. Calling delete q after delete p is always doomed to failure whether p was cleared or not.
<<
According to the standards, the behavior is undefined (that means the consequence can be from a simple error to the crash of the machine) and is implementation dependent.

>>
Not trying to be difficult. I genuinely don't see what you're trying to illustrate
here.
<<
You would if you wanted ( and not trying to be over-sympathetic ). I am trying to satisfy OP that this behavior of delete has a reason. But on the same time I am suggesting the OP, not to ask such questions relating to (why the hell this )standards ( is applied) . ( If you have a doubt and you feel that there is an error in the standard, bring a solution out)

>>
Please educate me - but be nice eh...
<<
You mean polite? Well sure, but not in the next 3 hrs atleast.
If you want more reference try getting something on Bjarne Stroustrup homepage :
http://www.research.att.com/~bs/bs_faq2.html#delete-zero

I hope the OP does get it, but I'm afraid I don't.

Didn't you mean: but I'm afraid he doesn't ?

>>Nothing would happen!
Just check on your part. You mean if compiler doesn't complain, everything is OK?
These are few of the undefined behaviors which means ( Effective C++ by Mayers gives a good info about Undefined behaviors) "anything can happen".
Or in other words it is implementation dependent.

>>! Are you a mindless idiot? Did your brain fall out? Did you replace it with a turd you found on the ground?
Answer to all these (useless) question is NO.

>>Answer: a complete and total moron, i.e., siddhantes!!! The OP's question was about the REASONING (something sid cannot comprehend) of the designers.

You are no one to judge my comprehension.

>>Don't worry about the "sidiot," as we shall call him. He has serious personality problems. Just ignore anything he says.
That was not funny. It was not in the same zipcode, funny.
I have a lot of other problems rather than dealing with my personality. Specially, I hate when people speak without having adequate knowledge.

>> Everybody else does!
Give me at least 5 names plz.

>>(P.S. The tone of the above is entirely contingent on the sidiot's original tone.)
May be, but my post was not as useless your is.

Yeah, siddhantes is right (look at the Bjarne Stroustrup's page) !
It isn't because it seems to work it's actually working (that's just C++) !

Useful link, thanks.
So, for the benefit of anyone else who didn't get that code, the point is that resetting p to NULL can be pointless since it is easily circumvented by copying the pointer.
Also interesting to see in that link that Bjarne says the standard doesn't prevent compilers from doing the reset (for lvalues) and he had hoped that more implementations would take this approach.

tux4life - does this pass the grammar check ;)

tux4life - does this pass the grammar check ;)

I don't know as I'm not a "native speaker" :P ...

Useful link, thanks.
So, for the benefit of anyone else who didn't get that code, the point is that resetting p to NULL can be pointless since it is easily circumvented by copying the pointer.
Also interesting to see in that link that Bjarne says the standard doesn't prevent compilers from doing the reset (for lvalues) and he had hoped that more implementations would take this approach.

Good to know now your getting on it. Phew.
Note that even though Stroustrup is father of C++, his job is not to write compilers. He may hope that implementors will do it someday but you may fail to think that it is not an easy job for the implementors
For the time being, just create your own function.

To summarize:
*Deleting a pointer to null is undefined behavior. But it is a bad bad practice.
[edit] Sorry it is a defined behavior. deleting a pointer to null won't do anything to the pointer. C++ guarantees this. http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.8
[/edit]
*Deleting a pointer twice is an udefined behaviour too.(though you may argue me that it gives you an error on your compiler) and is implementation dependent. Not to mention it is too a bad practice.
*Reseting to Null by delete is certainly not a good idea.
*(Sply to nucleon) Trying to be a hero(whose knowledge is doubtable) is certainly not a good idea.
*Being sympathetic to OP may be nice, but it solves nothing
*It doesn't really mater to OP how hard we fight, he will always win ;)

*Deleting a pointer twice is an udefined behaviour too.

Now is just the question left: To prevent deleting a pointer twice: how do we know a pointer has already been deleted :P ?
(I would solve that by implementing a new pointer type, but what's your vision on this?)

This thread is out of control.

To the OP: C++ was designed to allow the programmer to have nearly full control over what's happening in the program. Automatically assigning a pointer to NULL once it's been deleted is a waste of cpu, as once deleted, it's usually not used again until it's been reassigned.

Besides causing many other problems, here is an obvious reason not to.

char *buffer = new char[100];
delete[] buffer;
buffer = new char[50];

Would turn to:

char *buffer = new char[100];
delete[] buffer;
[B]buffer = NULL;[/B] // What's the point in this line
buffer = new char[50];

Or say that you have two dynamic objects which have both been deleted, but you still want to compare the original address to see if they were the same object. You would be unable to do so as all deleted objects point to NULL instead of their original adresses. The point is, the address can still be considered useful even after the data has been freed.

To siddhant3s: There's a difference bettween being rude and helpful. The OP asked a simple question which he learned from, so would it hurt to just be nice? :icon_rolleyes:

Siddhant3s: Wow, some response! You need to lay off the caffeine for a while.

1. I'm not demanding. I'm asking a history question -- why was this decision made? The answer may give me a better insight into the language or a neat new trick to use.
2. Your p = q; delete p; delete q example is bogus. The delete operator accepts a NULL pointer w/ no problem. (You do get a problem if you use a non-zero constant.)

By the way, I've programmed for over 30 years at HP and TI. I'm a part-time prof at a local university and I couldn't answer this question asked by a student.

1. I'm not demanding. I'm asking a history question

By the way, I've programmed for over 30 years at HP and TI. I'm a part-time prof at a local university and I couldn't answer this question asked by a student.

If that is true that you have programmed for over 30 years then you should already know the answer to your question, unless you have been programming with your head in the sand all those years.

*Being sympathetic to OP may be nice, but it solves nothing
*It doesn't really mater to OP how hard we fight, he will always win ;)

Actually I disagree. I don't know any C++ but I was attempting to learn the answer to the OP's question, and it was practically impossible to wade through all of the crap in this thread. Your attitude is despicable and you should be ashamed. Also, FYI, I did not learn anything from this thread. The egos blocked any possible gain of knowledge or understanding.

edit: Thanks to William, maybe I did learn something.

Also, FYI, I did not learn anything from this thread. The egos blocked any possible gain of knowledge or understanding.
.

This thread is not intended for beginners, so I'm not surprised you didn't learn a thing.

Hensworth -- Good response. I should have been clearer w/ my question since all the answers seem to be of the form: C/C++ is a minimalist language, as opposed to Pascal or ModCal for example. "Here's the chainsaw. Have fun but be careful."

Let me restate my question: I've been on standards committees. There's often lots of 'storm and stress' over passionate opinions. For example there's a (perhaps accurate?) quote from a C++ committee member: "We'd better add strings to this standard or there'll be blood in the streets!"

After deleting, your examples reuse the pointer one or two lines later. You know as well as I that there are a hundred different ways that you can execute through code and accidently miss initializing a pointer. This often results in a bug that only happens after 3 days of the program running and is a bear to debug.

So,
1. Was this discussed or fought about as the standard emerged? and
2. Is there some clever use in having the old address still around?

Hensworth -- Your "compare later to see if the memories were the same" is the closest so far to answering #2. But I think there are a lot safer ways to do this.

Anyway -- It may be as simple as what responders are saying: C/C++ likes to leave as much control in the programmer's hands as possible.

Thanks!

It's not Hensworth but Hemsworth :) ...

Sorry for my initial post. I thought this was a different type of forum than it is. Enjoy each other. I'm dropping out now.

1. Was this discussed or fought about as the standard emerged? and

The only people who would know the answer to that question are the people who sit on the ISO standards board. I doubt very very seriously that would include anyone at this web site. Anyone who says differently without ISO citations is just blowing smoke.

2. Is there some clever use in having the old address still around?

None that I know of. But since I don't know everything either, there could be some obscure clever use.

My 2 cents in this dogfight...

It seems there is a simple answer to the OP question:

delete this; // it's not a common case but it works

It's impossible to invent a reasonable interpretation for this evidently useful and sensible construct if delete pointer produces a side effect pointer = 0 : this is not l-value, we can't assign anything to not-l-value...

First of all my apologies for being out the thread for a while. I had my exams today. Just finished that and thus replying so late. Because of the exam I was not able to stay up last night.( remember I am +5.5hrs GMT).
I read all the posts after I tried to conclude this thread in post #16. But then too, the thread did not concluded hence I am making the second effort.

To the OP: C++ was designed to allow the programmer to have nearly full control over what's happening in the program. Automatically assigning a pointer to NULL once it's been deleted is a waste of cpu, as once deleted, it's usually not used again until it's been reassigned.

This is not actually the answer. Or if you stick to it, it is the answer to every problem in C++. Saying that a feature X has been added to 'get more control in the language' is no answer. I agree though, that automatically assigning a pointer to zero is a waste of cpu time.

Besides causing many other problems, here is an obvious reason not to.

This reason is not different from what I gave. But obviously this is not an obvious reason.
>>buffer = NULL; // What's the point in this line
There is of course a point in this line that the programmer wants to set buffer to zero. ( I though agree that there are very non-obvious cases where this is a wanted statement.)

Or say that you have two dynamic objects which have both been deleted, but you still want to compare the original address to see if they were the same object. You would be unable to do so as all deleted objects point to NULL instead of their original adresses. The point is, the address can still be considered useful even after the data has been freed.

Umm. Sorry but your beautiful reason of 'not having delete to reset the pointer to zero' is not valid.
The link[ 1 ] of Bjarne's homepage tells us that C++ standards doesn't restricts implementors to reset the pointer to zero. That means, on some ( maybe fictitious) compiler, the delete can actually set the pointer to zero! ( which is perfectly legal as per standards)
So giving advice to 'check the address, object initially pointed to' is not good (again, as per the standards).

To siddhant3s: There's a difference bettween being rude and helpful. The OP asked a simple question which he learned from, so would it hurt to just be nice?

Yes there is a difference. I was both. It won't of course hurt me to be nice, but those comments to OP was to make sure that he doesn't point out : “ Why the hell this feature was added/removed in standards”. These questions are not to be answered by anyone else the ISO committee members ( or else they cause thread like this)
------------------------------------------------------------------------

Siddhant3s: Wow, some response! You need to lay off the caffeine for a while.

Caffeine is my obsession. And I am proud of it.

1.I'm not demanding. I'm asking a history question -- why was this decision made? The answer may give me a better insight into the language or a neat new trick to use.

Promise me that you/ your students will not ask questions like these in forums like these. For the beginners of C++, The standards should be treated as Laws. For experienced programmers, these things will eventually clear up as you learn more and gain experience.

2.Your p = q; delete p; delete q example is bogus. The delete operator accepts a NULL pointer w/ no problem. (You do get a problem if you use a non-zero constant.)

Sure it does. But I think you ( or hardly anyone ) could understand the meaning of comment: “// Shit ! deleting pointer to null 0”
Look, ( I am wasting all this time so that a you don't commit this mistake in future) at least in C++, if an error is detected in compile time, it is the best thing you can get from the compiler. Run time error are very bad. (Even worst are logical errors) So, from that comment, I meant that now you cannot detect any error even if you delete an pointer twice (because you will be deleting zero pointer which won't raise alarms). In general, if your program is deleting a pointer twice, it suffers a flaw. Thus, you would never get to know that your program contained a flaw and hence you will be relaxed.
Another point to note is that the just above explanation was to satisfy you that ' not reseting to the pointer to zero after delete' is actually a good thing. You should never take into granted that delete will not reset the pointer to zero. Remember, after the execution of delete on an pointer, the value of the memory address passed by it is undefined ( as per the standards). Just like when you declared a new pointer without initializing it.
So if you delete a pointer, you cannot expect the value of that pointer to be null, the original value, or anything. Got it? I repeat, the value of a pointer after delete operation has been done is undefined.

By the way, I've programmed for over 30 years at HP and TI. I'm a part-time prof at a local university and I couldn't answer this question asked by a student.

I don't care. For me you are an OP. I can answer you thats why I am. Just this. Your programming experience is shown in your work and discussions.
(Phew Ancient, I always though you are so intelligent because of your experience, but now I realize that your intelligence and knowledge has nothing to do with your age.)

------------------------------------------

Also, FYI, I did not learn anything from this thread. The egos blocked any possible gain of knowledge or understanding.
edit: Thanks to William, maybe I did learn something.

Ancient has given you the reply, I would gave you. William as (undesirably) given you some wrong learnings though. But he was polite, so you followed him. This goes without saying that, that politeness will cost you a 14 hour bug in your program.
----------------------------------------------

The only people who would know the answer to that question are the people who sit on the ISO standards board. I doubt very very seriously that would include anyone at this web site. Anyone who says differently without ISO citations is just blowing smoke.

True, True, True.
------------------------------------------------

My 2 cents in this dogfight........

Save your money for your retirement.

It's impossible to invent a reasonable interpretation for this evidently useful and sensible construct if delete pointer produces a side effect pointer = 0 : this is not l-value, we can't assign anything to not-l-value...

Right. But as Dr. Stroustrup said, this could be a way to find errors during the compile time. Which is why he hopes that implementors will someday will implement delete so that it reset the pointer to zero.


To conclude:
*Deleting a null pointer is a defined behavior. It amounts to doing nothing.[ 2 ]
*Deleting a pointer twice is and undefined behavior. Though on most of the compilers, it will be a runtime error.[http://www.parashift.com/c++-faq-lite/freestore-mgmt.html]
*Reseting to Null by delete is certainly not a good idea( as it can propagate your bugs)[read my reply above to the post of OP]
*Reseting to Null by delete may be a good idea( since it can detect error on compile time if we try to delete a non- L-value. But this feature can of course be added by defining a function template as Stroustrup has done this in [ 1 ] )
*And the most important :
After deleting a pointer, you can never be sure what value it now has. Also, you will never be sure that what is the value pointed by it

I know this post was large, but it was important.
Hope that concludes the discussion.
[1] http://www.research.att.com/~bs/bs_faq2.html#delete-zero
[2] http://www.parashift.com/c++-faq-lite/freestore-mgmt.html

>>After deleting a pointer, you can never be sure what value it now has.

Disagree -- the pointer variable will contain the same address as it did before deleting it. The problem is the data at that address is subject to change at any time.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.