Re: malloc/free aimple question!
"Robby" <Robby@discussions.microsoft.com> wrote in message
news:022436AD-0CC0-4B21-B5DB-8A0CCD00A9DB@microsoft.com...
I am freeing p and leaving x alone. I was also tempted toset x to null,
but
thats dangerous too... no!
No :-) If you have a pointer which is non-NULL pointing to a piece of
memory you don't own, then it is very dangerous. A NULL pointer p can
cause problems if you do p->.... but sprinkling your debug code with
ASSERT(p); will usually soon force you to fix it before you release your
code to the world. An illegal non-NULL pointer can wreak much more havoc.
For this reason I usually set p=NULL; immediately after freeing the memory.
Danger yes, but a more controlled danger.
It can be useful to use blocks when doing this sort of thing:
{
long *p = malloc(....);
....
....
free(p);
}
Note that p has no existence before the line which mallocs, and none after
the line which frees. The { } block is used to protect the following code
from p by throwing it out of scope. You don't have to wait for an if, loop,
or function when using them.
Its just that in my real program, x and p are members of two different
structures which are typedefed in a header.
...
That is fine, (ish) but only one of them can "own" the data.
If we're doing C++ here, rather than C, the one which owns the data should
call malloc() in its constructor, (or at least set p to NULL if it is only
to be allocated later) and free() in its destructor. The other one
should take a copy of the pointer and have comments at regular intervals: I
DON'T OWN THIS DATA. DO NOT DESTROY THE OWNER WHILE I AM STILL AROUND.
Sometimes keeping track of an owner of data and other objects which only
contain access to it, is a useful approach, but it has to be done with care.
Alternatively, a more object oriented approach, is to malloc both of them,
and give them independent copies of the data, and then free them both.
(For malloc/free substitute new/delete in C++).
Dave
--
David Webber
Author of 'Mozart the Music Processor'
http://www.mozart.co.uk
For discussion/support see
http://www.mozart.co.uk/mozartists/mailinglist.htm