Allocation / Delete problems

H

Hamish Dean

Hi,

I have created a DLL which the user is complaining:

"Even when it works ok, my application stays instable (like something is
allocated or deleted in the wrong way)."

What does this mean? The way I have been allocating is:

int * pNew;
pNew = new int;

And deletion:

delete pNew;
pNew = NULL; /* what woudl happen here if i left this line out? or pNew = 0;
*/

Are there any problems with this code?
 
K

Kevin Goodsell

Hamish said:
Hi,

I have created a DLL which the user is complaining:

"Even when it works ok, my application stays instable (like something is
allocated or deleted in the wrong way)."

What does this mean? The way I have been allocating is:

int * pNew;
pNew = new int;

And deletion:

delete pNew;
pNew = NULL; /* what woudl happen here if i left this line out? or pNew = 0;
*/

Are there any problems with this code?

Only of you expect 'pNew = NULL;' to set to null ALL the pointer that
pointed to the deleted memory. If that's not the case, the problem is
probably elsewhere. Explicit memory management opens the door for all
kinds of errors, which is why it is best avoided.

-Kevin
 
B

Buster

Hamish said:
I have created a DLL which the user is complaining:

"Even when it works ok, my application stays instable (like something is
allocated or deleted in the wrong way)."

What does this mean? The way I have been allocating is:

int * pNew;
pNew = new int;

And deletion:

delete pNew;
pNew = NULL; /* what woudl happen here if i left this line out? or pNew = 0;
*/

Nothing would happen, and "0" and "NULL" are, roughly speaking,
the same. I prefer "0" because it's supported directly by the
language and doesn't depend on a macro definition in whatever
header it is.

You set a pointer to 0 in order to indicate that it doesn't point
to an object. This is sometimes useful. Sometimes the actual check
can be elided if all you want to do is "delete the object pointed to,
if any" (since "delete 0;" is a no-op). Sometimes you'll do an explicit
comparison.

If the pointer goes out of scope immediately after deletion,
setting it to 0 is a waste of time (but not much time).
Are there any problems with this code?

Not as written. But then, as written, it doesn't do anything.
Perhaps the control flow is not exactly as you think, and the
"delete" statement is not executed, or is executed more than
once, in some circumstances. You should probably be using RAII.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top