Openwall GNU/*/Linux - a small security-enhanced Linux distro for servers
[<prev] [next>] [<thread-prev] [day] [month] [year] [list]
Date: Mon, 14 Oct 2019 10:23:59 -0400
From: Rich Felker <dalias@...c.org>
To: musl@...ts.openwall.com
Subject: Re: [PATCH] Use open_memstream(3) for more efficient asprintf

On Mon, Oct 14, 2019 at 03:57:31PM +0200, Micha Nelissen wrote:
> On 14-10-2019 14:07, Rich Felker wrote:
> >- avoiding quadratic-time worst-case (from the memcpy in realloc with
> >   linear buffer size growth at each step) or internal fragmentation
> >   (from geometric buffer growth at each step). Our current memstream
> >   implementation uses linear growth I think so it would be the former
> >   (quadratic time)
> 
> This seems to imply linear buffer size growth doesn't cause
> fragmentation? In general it does I would assume.

It doesn't cause internal fragmentation (wasted space inside the
allocated block because too much was allocated). It still causes
external fragmentation.

> >- avoiding fragmentation produced by realloc
> 
> I guess the idea behind the original malloc(GUESS) (and also this
> memstream implementation?) is that it allocates from end of heap,
> and therefore realloc is very cheap: just move end of heap pointer.
> Although in a multi-threaded world this becomes less likely
> depending on the intensity of malloc/realloc usage by other threads.

The idea behind malloc(GUESS) was just to avoid two passes of
vsnprintf in the common case where the output is short; no
consideration of fragmentation was made. In general this kind of
pattern will result in breaking up of larger free areas rather than
using a suitable smaller one that's available. The malloc
implementation can mitigate this (and the future one will) by using
realloc as an opportunity to defragment, but that costs memcpy.

Note that one thing we could do, that would be better in almost all
ways, is make the first snprintf call write to an automatic (stack)
buffer of some reasonable size rather than null. Then, if the result
fit, we can just return strdup(buf) as the result rather than doing a
second pass.

Rich

Powered by blists - more mailing lists

Your e-mail address:

Confused about mailing lists and their use? Read about mailing lists on Wikipedia and check out these guidelines on proper formatting of your messages.