delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1999/12/22/09:50:44

From: Eric Sosman <esosman AT acm DOT org>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Problems with MALLOC and FREE
Date: Wed, 22 Dec 1999 14:35:48 +0000
Organization: AT&T WorldNet Services
Lines: 46
Message-ID: <38609B74.75D7B734@acm.org>
References: <Pine DOT SUN DOT 3 DOT 91 DOT 991209160149 DOT 22560D-100000 AT is> <82rh3j$sfu AT cantine DOT wu-wien DOT ac DOT at> <385EC088 DOT 8403BF22 AT ibm DOT net> <7GM74.500$PK3 DOT 5161 AT dfiatx1-snr1 DOT gtei DOT net> <385FE52F DOT E2F5572B AT east DOT sun DOT com> <RIX74.3450$PK3 DOT 29375 AT dfiatx1-snr1 DOT gtei DOT net>
NNTP-Posting-Host: 12.78.200.115
Mime-Version: 1.0
X-Trace: bgtnsc01.worldnet.att.net 945873293 9027 12.78.200.115 (22 Dec 1999 14:34:53 GMT)
X-Complaints-To: abuse AT worldnet DOT att DOT net
NNTP-Posting-Date: 22 Dec 1999 14:34:53 GMT
X-Mailer: Mozilla 4.61 [en] (Win95; U)
X-Accept-Language: en
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

Damian Yerrick wrote:
> 
> "Eric Sosman" <eric DOT sosman AT east DOT sun DOT com> wrote in message
> news:385FE52F DOT E2F5572B AT east DOT sun DOT com...
> > Damian Yerrick wrote:
> > > [...]
> > > Oh, by the way, does anyone know what the standard
> > > says should happen when you free(NULL)?
> >
> >     "If _ptr_ is a null pointer, no action occurs."
> 
> Simplifies things a bit.
> 
> #define Free(ptr)      free(ptr); ptr = NULL

    This is a poor idea on two counts.  First, the macro
expansion is faulty and will fail badly in situations like

	if (throw_it_away)
	    Free(ptr);

or (harder to fix)

	Type **ptr;
	...
	Free (*ptr++);

    The second drawback is that NULLing a free'd pointer may
give an illusion of security which is completely false.  If it
is to be effective, `ptr' must be the one and only copy of the
free'd pointer value anywhere in the program; setting `ptr' to
NULL will not affect any other now-invalid copies which may
reside elsewhere.  Note, for example, that if `ptr' is a
function argument, the proposed Free() macro (in a corrected
version) would only change the function's local copy, not the
original in the function's caller.

    It is much better -- in fact, it is essential -- to use
proper discipline in managing dynamic memory.  Write your
programs so that the responsibility for acquiring and releasing
memory (and other resources, for that matter) is well controlled,
and don't count on unreliable tricks to cover up carelessness.

-- 
Eric Sosman
esosman AT acm DOT org

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019