Path: 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 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!