Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!uflorida!haven!adm!smoke!gwyn
From: gwyn@smoke.BRL.MIL (Doug Gwyn)
Newsgroups: comp.lang.c
Subject: Re: Heap Fragmentation
Message-ID: <11184@smoke.BRL.MIL>
Date: 29 Sep 89 21:22:09 GMT
References: <1989Sep27.045926.12634@polyslo.CalPoly.EDU> <35076@apple.Apple.COM> <11161@smoke.BRL.MIL> <6643@thor.acc.stolaf.edu>
Reply-To: gwyn@brl.arpa (Doug Gwyn)
Organization: Ballistic Research Lab (BRL), APG, MD.
Lines: 23

In article <6643@thor.acc.stolaf.edu> mike@thor.stolaf.edu () writes:
>In article <11161@smoke.BRL.MIL> gwyn@brl.arpa (Doug Gwyn) writes:
>>... it would be unsafe for
>>a UNIX malloc()/free() implementation to shrink the heap in general.
>Not true.  GNU malloc(), of which I am the author, can shrink the heap.
>...  The algorithm is:
>	if (sbrk(0) == mallocs_notion_of_top_of_heap)
>		sbrk(negative_amount);

Well, I did say it's not safe to shrink it in general, not "in general,
it's not safe to shrink it".  In specific cases it can be safe.  Note,
however, that it's tricky to get right.  Consider the scenario:
	malloc() => sbrk(+)
	sbrk(+)
	malloc() => sbrk(+)
	free() => sbrk(-) by above algorithm
At this point malloc()/free() need to be able to determine where the
last malloc() arena heap-top is, to know that it's not at the current
sbrk(0).  You may have taken care of this extra bookkeeping requirement,
but it's easy to get wrong.  I put quite a bit of time a couple of
years ago into fixing all the bugs in the SVR2 malloc() (both of them);
I think that it did manage to keep synchronized with sbrk() although it
never tried to shrink the program break.