From mboxrd@z Thu Jan 1 00:00:00 1970 X-Msuck: nntp://news.gmane.org/gmane.linux.lib.musl.general/8488 Path: news.gmane.org!not-for-mail From: Rich Felker Newsgroups: gmane.linux.lib.musl.general Subject: Re: confusion about brk and mmap in expand_heap in malloc implementation Date: Thu, 10 Sep 2015 16:58:17 -0400 Message-ID: <20150910205817.GQ17773@brightrain.aerifal.cx> References: Reply-To: musl@lists.openwall.com NNTP-Posting-Host: plane.gmane.org Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Trace: ger.gmane.org 1441918714 27016 80.91.229.3 (10 Sep 2015 20:58:34 GMT) X-Complaints-To: usenet@ger.gmane.org NNTP-Posting-Date: Thu, 10 Sep 2015 20:58:34 +0000 (UTC) To: musl@lists.openwall.com Original-X-From: musl-return-8500-gllmg-musl=m.gmane.org@lists.openwall.com Thu Sep 10 22:58:34 2015 Return-path: Envelope-to: gllmg-musl@m.gmane.org Original-Received: from mother.openwall.net ([195.42.179.200]) by plane.gmane.org with smtp (Exim 4.69) (envelope-from ) id 1Za8vS-0007D4-BF for gllmg-musl@m.gmane.org; Thu, 10 Sep 2015 22:58:34 +0200 Original-Received: (qmail 5468 invoked by uid 550); 10 Sep 2015 20:58:31 -0000 Mailing-List: contact musl-help@lists.openwall.com; run by ezmlm Precedence: bulk List-Post: List-Help: List-Unsubscribe: List-Subscribe: Original-Received: (qmail 5428 invoked from network); 10 Sep 2015 20:58:30 -0000 Content-Disposition: inline In-Reply-To: User-Agent: Mutt/1.5.21 (2010-09-15) Original-Sender: Rich Felker Xref: news.gmane.org gmane.linux.lib.musl.general:8488 Archived-At: On Thu, Sep 10, 2015 at 02:58:33PM -0400, Yuxin Ren wrote: > Hi, > > I found in the __expand_heap function used by malloc, if brk fails, it will > use mmap to get a memory area. > I think in this case, this area should be returned back to system via > munmap. > But in my test, when I free such area, I found it is still passed to > madvise, not munmap. > > How do we track if an area is expanded by brk or mmap? > And when we free an area, how do we decide to use munmap or madvise? I think you're starting from some mistaken assumptions. The managed heap for small allocations (under a few hundred kb) is permanent for the lifetime of the process once it's allocated, whether it comes from brk or mmap. The only difference between the two approaches of obtaining memory is that brk is faster and makes it possible to obtain a contiguous range gradually rather than having to request large amounts at a time to ensure contiguity. Either way, what madvise does is free up the _physical_ memory backing large contiguous free areas on the heap. No attempt is made to free virtual address space (this would be a very bad idea; it could lead to heavy fragmentation) or commit charge. I have some ideas for freeing commit charge in the future, which may be desirable. Rich