How do I release a pointer to a sturcture in C++?

Hi,
I declare a pointer to a sturcture as follow:
IDispatch *pDisp=NULL;
At the clean up section of my code, how can I safely release this pointer?  My current code is getting me a error message of "Freeing freed memory"
if(pDisp)
    pDisp->Release;

Thank you.

lapuccaAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
AxterConnect With a Mentor Commented:
You should nullify your pointer after calling release.


if(pDisp)
{
    pDisp->Release;
    pDisp = NULL;
}

Open in new window

0
 
lapuccaAuthor Commented:
Really?  Do I have to do that for all pointer to anything or just structure?  I have to go over my code and correct all of them if so.  Let me try this and let you know if that would take care of my error.  Thank you.
0
 
jkrCommented:
Actually, that should be

if(pDisp)
    pDisp->Release();

Without the brackets, the statement is meaningless.
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
Infinity08Commented:
>> Do I have to do that for all pointer to anything or just structure?

Yes, otherwise, this check won't catch that the pointer has already been released :

        if(pDisp)
0
 
peprConnect With a Mentor Commented:
Technically, the pointer variable stores the addres of the memory space where the pointed thing is located. The NULL is a special constant that (technically zero) that says "pointing to nowhere".

In your case, you are pointint to the COM Dispatch interface, which is an object that represents the interface of some COM object to be accessed usually from an interpreted language.

If the pDisp were set to NULL, the pDisp is interpreted as false in a boolean context (the if condition). Otherwise, it is interpreted as true in the boolean context. In the body of the if control structure, you are calling the method of the pointed object (i.e. pDisp->Release();)  If the object exists, then it is fine. If the object does not exist, then it is an error.

Actually, you do not need to assign NULL to a pointer after deleting the pointed object if you are sure that the pointer is never to be used any more. However, you never know who and how the source code will be modified later. The rule of thumb is to always assign NULL to pointers that should be invalidated.
0
 
jkrCommented:
Funny, so that worked using

pDisp->Release;

?

Wow, C++ never stops surprising me...
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.