From: Stephen Irons Newsgroups: comp.os.msdos.djgpp Subject: Re: free() Date: Thu, 25 Jun 1998 16:54:39 +1200 Organization: None Lines: 64 Message-ID: <3591D80E.54EF@usa.net> References: <19980623 DOT 131350 DOT 7759 DOT 0 DOT zixyer AT juno DOT com> Reply-To: stephen DOT irons AT usa DOT net NNTP-Posting-Host: 210-55-236-69.static-dialup.xtra.co.nz Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Precedence: bulk Zixyer S Qwerty wrote: > > How does free() know how much memory to return to the heap? Does it have > to be the originally malloc()ed pointer or can it be a different pointer > to the memory that was allocated? I'm writing a linked list and keeping > pointers to each element around kinda defeats the purpose... thanks in > advance for any help > > _____________________________________________________________________ > You don't need to buy Internet access to use free Internet e-mail. > Get completely free e-mail from Juno at http://www.juno.com > Or call Juno at (800) 654-JUNO [654-5866] The pointer must have the same value, but does not have to have the same name. For example, you could do the following: char * p1; char * p2; p1 = malloc(1000); /* p1 points to a block of memory */ p2 = p1; /* p2 points to the same block */ free (p2); /* p1 and p2 point to the same block */ /* but you aren't allowed to use it any more. */ So your linked list will work fine. This issue is where memory leaks and GPFs come from. If p1 and p2 go out of scope before you free(), you still have the block of memory, but no pointer to it to free() it, so you can't free it. If you use p1 or p2 after free()-ing, the memory may have been allocated to another application, and you memory management unit will cause a memory protection fault. The way malloc() and free() usually work is by allocating a block of memory bigger than you ask for, putting a header right at the start, then giving you a pointer to the rest of the block. The header will remember a number of things: how big the block is, where it came from, and so on. For example, if you request 1024 bytes, malloc(1024) might get a block of 1030 bytes from the operating system at address 0x1000 (say). Then malloc() puts an 8-byte header at 0x1000, and returns 0x1008 to you. So you happily store your data at 0x1008 onwards. When you release the memory, free() subtracts the header size from the address you give it, so that it can find out how big the block was and how to release it. You can find out what is in the malloc() header by reading the source code for malloc(). But don't rely all implementations using the same header: there are lots of alternative dynamic memory allocation algorithms.