473,883 Members | 3,134 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Set a pointer to null when deleting?

When you delete a pointer, you should set it to NULL, right?

Joe
Apr 10 '06
51 10591
Phlip wrote:
Noah Roberts wrote:
p = getPointerFromW hatever();
if (p)
p->method(42); p = getPointerFromW hatever();
assert(p);
p->method(42);

The code is one tick simpler; it has one less 'if' statement.


Really? What is that assert doing there then?


It is not increasing the mental burden of reading the function.


I find the if(p) version less burdensome to read, and simpler.
You mention that the assert version is "simpler" because it
does not have a "control structure". But the assert() is
performing control flow. What's worse is that that flow
is opaque: what happens when the assert fails? We can't
tell from this example. But in the if() code, if p is null
then we know exactly what will happen (the code will
continue on with whatever statements follow this snippet).

Apr 10 '06 #31

Old Wolf wrote:
I find the if(p) version less burdensome to read, and simpler.
You mention that the assert version is "simpler" because it
does not have a "control structure". But the assert() is
performing control flow. What's worse is that that flow
is opaque: what happens when the assert fails? We can't
tell from this example. But in the if() code, if p is null
then we know exactly what will happen (the code will
continue on with whatever statements follow this snippet).


I think for most cases the if (p) version is adiquate, simplest, and
more easily read/dealt with. There are some cases when a null object
is better such as when dealing with states where there can be a 'null'
state. If you have a bunch of polymorphic objects implementing an
abstract interface anyway it can be better to implement the null
condition with an actual object than with a 0 pointer...somet imes.
However, replacing every occurance of 'if(p)' with a null object is
crazyness and if you have no control over the class you are pointing to
it just plain won't work in most cases.

Apr 10 '06 #32
Old Wolf wrote:
Phlip wrote:
Noah Roberts wrote:

p = getPointerFromW hatever();
if (p)
p->method(42);

p = getPointerFromW hatever();
assert(p);
p->method(42);

The code is one tick simpler; it has one less 'if' statement.

Really? What is that assert doing there then?


It is not increasing the mental burden of reading the function.

I find the if(p) version less burdensome to read, and simpler.
You mention that the assert version is "simpler" because it
does not have a "control structure". But the assert() is
performing control flow. What's worse is that that flow
is opaque: what happens when the assert fails? We can't
tell from this example. But in the if() code, if p is null
then we know exactly what will happen (the code will
continue on with whatever statements follow this snippet).

Potentially dangerous without an else?

I'm not supporting the assert alternative, but there should be some
error handling. On a lot of systems, the assert would be largely
superfluous as attempting to dereference the (NULL) pointer would case a
crash.

--
Ian Collins.
Apr 10 '06 #33

Ian Collins wrote:
Potentially dangerous without an else?

I'm not supporting the assert alternative, but there should be some
error handling. On a lot of systems, the assert would be largely
superfluous as attempting to dereference the (NULL) pointer would case a
crash.


Well, in this case, the original code that used the assert used a 'null
object'. It was used as an argument for such constructs and the
question of how it applied was never really adiquately answered. The
idea was that with a normal pointer you had to use an if (p) p->do()
where with a null object you would assert(p); p->do();...and this is
simpler...

- shrug -

Apr 11 '06 #34

Noah Roberts skrev:
C. J. Clegg wrote:
On Mon, 10 Apr 2006 13:58:52 GMT, Joe Van Dyk <jo********@boe ing.com>
wrote:
> When you delete a pointer, you should set it to NULL, right?
You don't HAVE to.
doesn't hurt and is often helpful.

It is not always helpful. Also the ptr = 0 sends the wrong message to
the reader - is the pointer reset now and then or what is it that takes
place. And there it is. There is no reason NOT to beyond linespace fetishes.
There is one very good reason: to verify your program logic. Accessing
a resource that is no longer present is an obvious programming error,
and setting the pointer to 0 might just prevent that situation from
being identified.
If you are going to set the pointer to anything, it is a far better
idea to set it to some illegal value the same way as operator delete
sets memory to an often illegal pattern in some debug builds.
If the pointer is used to designate an optional value, the situation is
different and you should set the pointer to 0. It can save from hours to days debugging. In fact, if you set your
pointers to 0 all the time then some bugs will never bite you that
otherwise would have taken hours or days to debug. Deleting a 0
pointer is not an error, deleting any other pointer that has been
deleted already is and can be one of the most difficult types of errors
to track down.

It is one minor step you can use to help you keep bugs out of your
programs. Scope isn't the issue, getting in the habit of ALWAYS doing
it benefits you in numerous ways.


Also notice that the reset will not always prevent the error. Actually,
I believe that it will do so only in the most trivial of situations.
The OPs problem would not be solved by setting the pointer to 0, for
example.

/Peter

Apr 11 '06 #35
Ian Collins wrote:
I'm not supporting the assert alternative


There never was an assert() alternative. The question was raised why
advanced programmers were not simply declaring all dead pointers should be
NULLed. I brought in NullObjects as an advanced alternative. The assert()
was to prevent nitpicking. A better implementation would hide the pointer,
and its assertions, and pass around a reference.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Apr 11 '06 #36

peter koch wrote:
Noah Roberts skrev:
C. J. Clegg wrote:
On Mon, 10 Apr 2006 13:58:52 GMT, Joe Van Dyk <jo********@boe ing.com>
wrote:

>> When you delete a pointer, you should set it to NULL, right?

You don't HAVE to.
doesn't hurt and is often helpful.

It is not always helpful. Also the ptr = 0 sends the wrong message to
the reader - is the pointer reset now and then or what is it that takes
place.


ptr = 0 is well defined. Everyone that is familiar with the language
knows exactly what it does.
And there it is. There is no reason NOT to beyond linespace fetishes.


There is one very good reason: to verify your program logic. Accessing
a resource that is no longer present is an obvious programming error,
and setting the pointer to 0 might just prevent that situation from
being identified.


Not true.
If you are going to set the pointer to anything, it is a far better
idea to set it to some illegal value the same way as operator delete
sets memory to an often illegal pattern in some debug builds.
This idea is very non-portable for one and doesn't follow standard
practice. Talk about being difficult to understand...

There is absolutely no reason to go looking for some other value to set
a pointer to. All that does is introduce problems in both
understandabili ty, platform dependance, and undefined behavior.
If the pointer is used to designate an optional value, the situation is
different and you should set the pointer to 0.
It can save from hours to days debugging. In fact, if you set your
pointers to 0 all the time then some bugs will never bite you that
otherwise would have taken hours or days to debug. Deleting a 0
pointer is not an error, deleting any other pointer that has been
deleted already is and can be one of the most difficult types of errors
to track down.

It is one minor step you can use to help you keep bugs out of your
programs. Scope isn't the issue, getting in the habit of ALWAYS doing
it benefits you in numerous ways.


Also notice that the reset will not always prevent the error. Actually,
I believe that it will do so only in the most trivial of situations.
The OPs problem would not be solved by setting the pointer to 0, for
example.


The problem of deleting a pointer that was already deleted, the problem
I was talking about in the quote above, will ALWAYS be solved by
setting the pointer's value to 0. No other access can be solved in
this manner beyond the fact that you can now check the pointer's value
before accessing it...just as delete does.

Apr 11 '06 #37

Phlip wrote:
Ian Collins wrote:
I'm not supporting the assert alternative


There never was an assert() alternative. The question was raised why
advanced programmers were not simply declaring all dead pointers should be
NULLed. I brought in NullObjects as an advanced alternative. The assert()
was to prevent nitpicking. A better implementation would hide the pointer,
and its assertions, and pass around a reference.


Dude, the null object pattern has its place, and it isn't _everywhere_.

Apr 11 '06 #38

"Phlip" <ph******@yahoo .com> wrote in message
news:2h******** *********@newss vr33.news.prodi gy.com...
Ian Collins wrote:
I'm not supporting the assert alternative


There never was an assert() alternative. The question was raised why
advanced programmers were not simply declaring all dead pointers should be
NULLed.


Phlip,

If you're referring to my statement "I'm a little surprised at the responses
you've been getting from some very experienced programmers.", what I meant
was that I'm surprised that in response to a very specific question the
replies were "smart pointer" and some guesses about what the pointer is
actually pointing at. I'm not at all surprised that experienced programmers
would not advocate "set all dead pointers to NULL." Over the years I've come
to the conclusion that mindlessly adding good- practice code snippets can do
more harm than good.

Andrew
Apr 11 '06 #39

Noah Roberts skrev:
peter koch wrote:
Noah Roberts skrev:
C. J. Clegg wrote:
> On Mon, 10 Apr 2006 13:58:52 GMT, Joe Van Dyk <jo********@boe ing.com>
> wrote:
>
> >> When you delete a pointer, you should set it to NULL, right?
>
> You don't HAVE to.
> doesn't hurt and is often helpful.
It is not always helpful. Also the ptr = 0 sends the wrong message to
the reader - is the pointer reset now and then or what is it that takes
place.


ptr = 0 is well defined. Everyone that is familiar with the language
knows exactly what it does.

Surely, But the reader asks "why" and thats a different question to
answer.
And there it is. There is no reason NOT to beyond linespace fetishes.
There is one very good reason: to verify your program logic. Accessing
a resource that is no longer present is an obvious programming error,
and setting the pointer to 0 might just prevent that situation from
being identified.


Not true.

Sure? Examples given in this thread would specifically behave that way.
Far to often you write if (p != 0) p->action() instead of assert(p !=
0); p->action();
If you are going to set the pointer to anything, it is a far better
idea to set it to some illegal value the same way as operator delete
sets memory to an often illegal pattern in some debug builds.
This idea is very non-portable for one and doesn't follow standard
practice. Talk about being difficult to understand...

There is absolutely no reason to go looking for some other value to set
a pointer to. All that does is introduce problems in both
understandabili ty, platform dependance, and undefined behavior.

That is a small problem as this is only something to do while
debugging.
If the pointer is used to designate an optional value, the situation is
different and you should set the pointer to 0.
It can save from hours to days debugging. In fact, if you set your
pointers to 0 all the time then some bugs will never bite you that
otherwise would have taken hours or days to debug. Deleting a 0
pointer is not an error, deleting any other pointer that has been
deleted already is and can be one of the most difficult types of errors
to track down.

It is one minor step you can use to help you keep bugs out of your
programs. Scope isn't the issue, getting in the habit of ALWAYS doing
it benefits you in numerous ways.


Also notice that the reset will not always prevent the error. Actually,
I believe that it will do so only in the most trivial of situations.
The OPs problem would not be solved by setting the pointer to 0, for
example.


The problem of deleting a pointer that was already deleted, the problem
I was talking about in the quote above, will ALWAYS be solved by
setting the pointer's value to 0. No other access can be solved in
this manner beyond the fact that you can now check the pointer's value
before accessing it...just as delete does.

Right. But that is a trivial situation - in all respects. Typically you
instead have two pointers pointing to the same object and delete one of
these. A problem that can't be solved without using smart pointers (or
discipline).

/Peter

Apr 11 '06 #40

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

Similar topics

2
2346
by: Asfand Yar Qazi | last post by:
Hello. Partly for learning purposes, I have written a smart pointer class. Could you please tell me what's wrong with it? (I know there's something wrong with it, but just not what!) Note that, as well as reference counting the stored pointer, it also has the ability to be declared for incomplete types (I think). I.e.: struct Incomplete;
2
1371
by: nifsmith | last post by:
Hi I am creating my own Queue class to learn about Queues and pointers. I have come across a question of two styles and I don't know if there are any dangers associated with them. I coded my remove function as follows template <class T>
3
9634
by: Songling | last post by:
Hi gurus, Just learnt from my co-worker that it's safe to delete a null pointer. I tried it on sun box (and linux), nothing bad happens. So it seems to be true. But does it apply to all platforms? Also if I delete a pointer twice, and don't nullify the pointer after the first delete, it's going to trap. If I do the nullify, no trap. Does it just confirm that it's safe
4
3112
by: Venn Syii | last post by:
I've searched all the forums but cannot find an answer to this question. I do the following: vector<MyClass*> myClassList; Later in the program I try to add to myClassList with a .push_back(...) I get an "out of memory" runtime error. I know I'm not out of memory because normal vectors such as vector<int> a, still work, and still work fine.
3
3412
by: John Ratliff | last post by:
When I dereference a pointer, does it make a copy of the object? Say I had a singleton, and wanted an static method to retrieve it from the class. class foo { private: static foo *bar; foo() {} // no public creation!
6
3032
by: KWienhold | last post by:
I'm currently working on a project in C# (VS 2003 SP1, .Net 1.1) that utilizes IStream/IStorage COM-Elements. Up to now I have gotten everything to work to my satisfaction, but now I have come across a problem I can't really explain: When deleting an object from an IStorage, the space it used up will not be freed, but rather marked as unused and overwritten the next time you add an object to the storage. This is obviously working as...
30
2762
by: Jess | last post by:
Hello, I tried a program as follows: include<iostream> using namespace std; class A{ public:
6
1997
by: ma740988 | last post by:
Given the snippet. class foo { public: ~foo() { // type id should be able to get the type of the class ( I think ) std::cout << " foo destructing " << std::endl; } };
8
6148
by: Rahul | last post by:
Please read the following code class Test{ public: void * operator new (size_t t) { return malloc(t); } void operator delete (void *p) { free(p); } };
0
9797
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,...
0
10762
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
10863
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
10422
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
9586
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
7136
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
5807
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...
1
4622
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
4228
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.