🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.sys.ibm.pc
Article #41325

Re: Freeing allociated memory.

#41325
From: Jeff Pipkins
Date: Thu, 11 Jan 1990 23:51
36 lines
1970 bytes
In article <1990Jan10.202458.17223@resrch.molienergy.bc.ca> jamesd@resrch.molienergy.bc.ca (James Dudley) writes:
>Hello to all:
>
>I am experiencing a problem with freeing memory allociated which was
>allociated with malloc().   Consider the following code.
>
>char *buf, *lineptr[2000];
>
>if (buf = (char *) malloc(fsize*sizeof(char)) == NULL)  {
>   print error message and return
>}
>lineptr[0] = buf;
>     do stuff
>/* now free allociated memory */
>free((void *) buf);
>
>Free() doesnot appear to deallociate the memory because I am using a 
>routine to traverse the Heap and report back Free and Unused blocks.
>

The problem is not with free().  The memory is allocated, but the variable
buf will not point to it!  In the "if" statement above, the == operator
has higher precedence than the = operator.  The memory will be allocated
and then the pointer returned will be compared to NULL.  If the request
is granted, the comparison will be false, and so the value of 0 will be
assigned to buf, effectively making it a NULL pointer.  The call to free()
will then try to free memory that has not been allocated with malloc(),
and the block allocated by malloc() will, of course, remain.  Also note
that free(NULL) can cause disastrous results, and should be regarded as "BAD".

To avoid this mess, just add another set of parentheses, like so:

   if ( (buf = (char *) malloc(fsize*sizeof(char)) ) == NULL) 
	^                                          ^

Hope this helps!
Technical Details
Message-ID: <83@qmsseq.imagen.com>
Path: arc1-ca.pugleaf.net!utzoo!attcan!uunet!aplcen!samsung!usc!apple!fox!portal!atari!imagen!qmsseq!pipkins
References: <1990Jan10.202458.17223@resrch.molienergy.bc.ca>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!attcan!uunet!aplcen!samsung!usc!apple!fox!portal!atari!imagen!qmsseq!pipkins
From: pipkins@qmsseq.imagen.com (Jeff Pipkins)
Newsgroups: comp.sys.ibm.pc
Subject: Re: Freeing allociated memory.
Message-ID: <83@qmsseq.imagen.com>
Date: 11 Jan 90 23:51:04 GMT
References: <1990Jan10.202458.17223@resrch.molienergy.bc.ca>
Reply-To: pipkins@qmsseq.UUCP (Jeff Pipkins)
Distribution: na
Organization: QMS Inc., Mobile, Alabama
Lines: 36