473,378 Members | 1,139 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,378 software developers and data experts.

test to see if object exists with new/delete usage

I create a pointer to an item:

CardSession *cardSession;

Then, later, I use new to create an instance of the item and assign it
to that pointer:

cardSession = new CardSession();

In another function, I want to test if an object is assigned to that
pointer, and delete the object if that is so:

if( cardSession )
delete cardSession;

I thought this would work, but then I discovered that, if cardSession
had *ever* been assigned a CardSession object with new, then the if
statement executes the delete command, even if the object had since been
deleted. Thus, I sometimes get an item doubly deleted with this code -
an undefined behavior that I think is causing my program to crash. Note
that if I have not yet used new in the program to assign an object to
cardSession, the if statement does not execute.

Could somebody explain this to me? Am I not understanding pointer usage
correctly, or is it innapropriate usage of new/delete? How can I do
this in an efficient fashion, without managing a global pointer to be
modified everytime I create or delete an object?
Jul 23 '05 #1
11 23014
Squid Seven wrote:
I create a pointer to an item:

CardSession *cardSession;

Then, later, I use new to create an instance of the item and assign it
to that pointer:

cardSession = new CardSession();

In another function, I want to test if an object is assigned to that
pointer, and delete the object if that is so:

if( cardSession )
delete cardSession;

I thought this would work, but then I discovered that, if cardSession
had *ever* been assigned a CardSession object with new, then the if
statement executes the delete command, even if the object had since been
deleted. Thus, I sometimes get an item doubly deleted with this code -
an undefined behavior that I think is causing my program to crash. Note
that if I have not yet used new in the program to assign an object to
cardSession, the if statement does not execute.

Could somebody explain this to me? Am I not understanding pointer usage
correctly, or is it innapropriate usage of new/delete? How can I do
this in an efficient fashion, without managing a global pointer to be
modified everytime I create or delete an object?


meant to say "without managing a global *flag* to be..." - sorry
Jul 23 '05 #2
> I create a pointer to an item:

CardSession *cardSession;
Note that the pointer may not have NULL value here.
[...] In another function, I want to test if an object is assigned to that
pointer, and delete the object if that is so: if( cardSession )
delete cardSession;
This does not test if the pointer points to an object.
I thought this would work, but then I discovered that, if cardSession
had *ever* been assigned a CardSession object with new, then the if
statement executes the delete command, even if the object had since been
deleted. Thus, I sometimes get an item doubly deleted with this code -
an undefined behavior that I think is causing my program to crash. Note
that if I have not yet used new in the program to assign an object to
cardSession, the if statement does not execute.


Depends on cardSessions's value obviously. You may explicitly set the
pointer to NULL initially or after deleting the pointed to object. It's
safe to call delete cardSession when cardSession==NULL.

Regards,
Matthias

Jul 23 '05 #3
Squid Seven wrote:
I create a pointer to an item:

CardSession *cardSession;
Change this to

CardSession *cardSession = null;

It's good practice to initialize the variable.
if( cardSession )
delete cardSession;

I thought this would work, but then I discovered that, if cardSession
had *ever* been assigned a CardSession object with new, then the if
statement executes the delete command, even if the object had since been
deleted.


Yes. Either you don't understand what if(cardSession) does, or you don't
understand what delete does. For a pointer type such as the variable you
have here, the conditional

if(cardSession)

is a check to see whether cardSession is a null pointer or not--it does
NOT check if the pointed-to object is valid (and there is no way in
general to perform such a check in standard C++).

The subsequent delete statement destroys whatever is pointed to by
cardSession. If a valid object isn't there, you are likely to crash.

What you need to do here, and what is also good practice, is to add this
after you delete:

cardSession = null;

Also be aware that your check for whether cardSession is null is not
necessary. It is perfectly safe to delete a null pointer (but not an
invalid one), so just

delete cardSession;
cardSession=null;

in place of your original "if" will do the job.

-cjm
Jul 23 '05 #4
Matthias Kluwe wrote:
I create a pointer to an item:

CardSession *cardSession;

Note that the pointer may not have NULL value here.

[...]


In another function, I want to test if an object is assigned to that
pointer, and delete the object if that is so:


if( cardSession )
delete cardSession;

This does not test if the pointer points to an object.

I thought this would work, but then I discovered that, if cardSession
had *ever* been assigned a CardSession object with new, then the if
statement executes the delete command, even if the object had since been
deleted. Thus, I sometimes get an item doubly deleted with this code -
an undefined behavior that I think is causing my program to crash. Note
that if I have not yet used new in the program to assign an object to
cardSession, the if statement does not execute.

Depends on cardSessions's value obviously. You may explicitly set the
pointer to NULL initially or after deleting the pointed to object. It's
safe to call delete cardSession when cardSession==NULL.

Regards,
Matthias

OK - let me see if I follow... When I create the pointer, if I don't
initialize it to something, I don't know what it's pointing at - could
be null, could not be. Then, when I delete the object associated with
the pointer, while I am indicating that the memory pointed at is
available for other use, the pointer still points at that memory, until
assigned to something else, and so causes the if statement to execute
it's contents?

Also, if this does not test if the pointer points to an object, how do I
test for it?

Thanks for your time Matthias
Jul 23 '05 #5
Me


Squid Seven wrote:
I create a pointer to an item:

CardSession *cardSession;

Then, later, I use new to create an instance of the item and assign it
to that pointer:

cardSession = new CardSession();

In another function, I want to test if an object is assigned to that
pointer, and delete the object if that is so:

if( cardSession )
delete cardSession;
Unless you overloaded a new operator to have a throw() somewhere, the
default one doesn't return null on failure, it throws bad_alloc. Also,
you don't need to check for null when you delete, the delete operator
does that check for you.
I thought this would work, but then I discovered that, if cardSession
had *ever* been assigned a CardSession object with new, then the if
statement executes the delete command, even if the object had since been
deleted. Thus, I sometimes get an item doubly deleted with this code -
an undefined behavior that I think is causing my program to crash. Note
that if I have not yet used new in the program to assign an object to
cardSession, the if statement does not execute.

Could somebody explain this to me? Am I not understanding pointer usage
correctly, or is it innapropriate usage of new/delete? How can I do
this in an efficient fashion, without managing a global pointer to be
modified everytime I create or delete an object?


Ok, I see what you're trying to do. delete is allowed to set the
pointer to null, but most implementations, like yours, don't do that.
So you have to explicitly write this as:

delete cardSession;
cardSession = 0;

This doesn't work if you do:

void foo(Card *c)
{
delete c;
c = 0;
}

Card *c = new Card();
foo(c);
// c points to garbage instead of null

You can rewrite that as:

void foo(Card *&c)
{
delete c;
c = 0;
}

and now it will correctly set the c that was passed to foo() to null.

Jul 23 '05 #6


Chad J McQuinn wrote:
Squid Seven wrote:
I create a pointer to an item:

CardSession *cardSession;

Change this to

CardSession *cardSession = null;

It's good practice to initialize the variable.
if( cardSession )
delete cardSession;

I thought this would work, but then I discovered that, if cardSession
had *ever* been assigned a CardSession object with new, then the if
statement executes the delete command, even if the object had since
been deleted.

Yes. Either you don't understand what if(cardSession) does, or you don't
understand what delete does. For a pointer type such as the variable you
have here, the conditional

if(cardSession)

is a check to see whether cardSession is a null pointer or not--it does
NOT check if the pointed-to object is valid (and there is no way in
general to perform such a check in standard C++).

The subsequent delete statement destroys whatever is pointed to by
cardSession. If a valid object isn't there, you are likely to crash.

What you need to do here, and what is also good practice, is to add this
after you delete:

cardSession = null;

Also be aware that your check for whether cardSession is null is not
necessary. It is perfectly safe to delete a null pointer (but not an
invalid one), so just

delete cardSession;
cardSession=null;

in place of your original "if" will do the job.

-cjm


When I try:

CardSession *cardSession = null;

I get the error message "'null' was not declared in this scope." Is
that a compiler-specific issue? Can I simply use:

CardSession *cardSession = 0;

as someone else suggested, and still not have to test before calling delete?

Thanks much for helping out a newbie guys.
Jul 23 '05 #7


Squid Seven wrote:


Chad J McQuinn wrote:
Squid Seven wrote:
I create a pointer to an item:

CardSession *cardSession;


Change this to

CardSession *cardSession = null;

It's good practice to initialize the variable.
if( cardSession )
delete cardSession;

I thought this would work, but then I discovered that, if cardSession
had *ever* been assigned a CardSession object with new, then the if
statement executes the delete command, even if the object had since
been deleted.


Yes. Either you don't understand what if(cardSession) does, or you
don't understand what delete does. For a pointer type such as the
variable you have here, the conditional

if(cardSession)

is a check to see whether cardSession is a null pointer or not--it
does NOT check if the pointed-to object is valid (and there is no way
in general to perform such a check in standard C++).

The subsequent delete statement destroys whatever is pointed to by
cardSession. If a valid object isn't there, you are likely to crash.

What you need to do here, and what is also good practice, is to add
this after you delete:

cardSession = null;

Also be aware that your check for whether cardSession is null is not
necessary. It is perfectly safe to delete a null pointer (but not an
invalid one), so just

delete cardSession;
cardSession=null;

in place of your original "if" will do the job.

-cjm

When I try:

CardSession *cardSession = null;

I get the error message "'null' was not declared in this scope." Is
that a compiler-specific issue? Can I simply use:

CardSession *cardSession = 0;

as someone else suggested, and still not have to test before calling
delete?

Thanks much for helping out a newbie guys.


Oh, it was compiler-dependent. I need to use 'NULL', not 'null'.

All set now, thanks much.
Jul 23 '05 #8
Squid Seven wrote:

CardSession *cardSession = null;

I get the error message "'null' was not declared in this scope." Is
that a compiler-specific issue? Can I simply use:

CardSession *cardSession = 0;

as someone else suggested, and still not have to test before calling
delete?


Yes, sorry about that, it should be 'NULL' (not 'null') which should be
a #define for 0, so those two should be equivalent. This is in C++; in
plain C, as well as with some older compilers, you might see it #defined
to something else, such as (void*)0, which causes problems. For this
reason you'll see a lot of people use a literal zero as you just did. It
also avoids having to remember if it's NULL or null. :)

-cjm
Jul 23 '05 #9
> OK - let me see if I follow... When I create the pointer, if I don't
initialize it to something, I don't know what it's pointing at - could
be null, could not be. Then, when I delete the object associated with
the pointer, while I am indicating that the memory pointed at is
available for other use, the pointer still points at that memory, until
assigned to something else, and so causes the if statement to execute
it's contents?
Exactly. You cannot rely on the value of an unitialized variable
(pointer or not). You cannot rely on a pointer of some type pointing to
an object of this type (you have to care by yourself).
Also, if this does not test if the pointer points to an object, how do I
test for it?


As said in the thread, you can assing the value 0 (or NULL if you
really like to) to indicate no object is pointed to.

Alternatively, program logic should ensure that some function handling
the pointer is only called when this makes sense ...

Regards,
Matthias

Jul 23 '05 #10
The short answer, hidden in all these replies is: use this idiom:

CardSession* cardSession = 0;
....

if (cardSession) {delete cardSession; cardSession = 0;}

Stuart

Jul 23 '05 #11
Me schreef:
Ok, I see what you're trying to do. delete is allowed to set the
pointer to null


Actually, it isn't. The pointer being deleted might be const and/or
volatile, in which case a write would be bad news. Of course, IF the
ocmpiler can prove it doesn't matter, it might do so - but if it
provably doesn't matter, why bother?

Regards,
Michiel Salters

Jul 23 '05 #12

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

Similar topics

8
by: StepH | last post by:
Hi, I've this module : from optparse import OptionParser import re _version = "P1" def writeVar(f, line):
25
by: Treetop | last post by:
I have seen some codes that can test for the browser and give values accordingly. I tried to read the FAQ, but was unable to find a simple version of this. What I want is If Netscape-test {...
15
by: Rick | last post by:
Hi, Does deleting an object more than one times incur undefined behavior? I think it doesn't but just making sure... thanks Rick
54
by: tshad | last post by:
I have a function: function SalaryDisplay(me) { var salaryMinLabel = document.getElementById("SalaryMin"); salaryMinLabel.value = 200; alert("after setting salaryMinLabel = " +...
2
by: Bob | last post by:
How can I reuse an object that is already defined. I want to delete some files using the FileInfo class and the "name" is a read only property so I can't set the name as I want to. I don't want to...
0
by: Roman | last post by:
I'm trying to create the form which would allow data entry to the Client table, as well as modification and deletion of existing data rows. For some reason the DataGrid part of functionality stops...
15
by: cedgington | last post by:
I wanted to take advantage of the large set of functionality offered by the framework, so for my latest project I'm using managed C++ with .NET v2. I'm using the gcnew operator in two different...
12
by: Belebele | last post by:
Suppose that a class A depends on class B because an object of class B is passed into A's constructor. See below: class B { ... }; class A { public: A(B const& b); ... };
176
by: nw | last post by:
Hi, I previously asked for suggestions on teaching testing in C++. Based on some of the replies I received I decided that best way to proceed would be to teach the students how they might write...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.