From: Eric Sosman 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: <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> NNTP-Posting-Host: 12.78.200.115 Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit 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" 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