This is the mail archive of the
libc-alpha@sourceware.org
mailing list for the glibc project.
Re: Policy: alloca vs. malloc?
- From: Siddhesh Poyarekar <siddhesh dot poyarekar at gmail dot com>
- To: "Carlos O'Donell" <carlos_odonell at mentor dot com>
- Cc: libc-alpha <libc-alpha at sourceware dot org>, Roland McGrath <roland at hack dot frob dot com>
- Date: Fri, 8 Jun 2012 08:29:15 +0530
- Subject: Re: Policy: alloca vs. malloc?
- References: <4FD0E4DC.1000105@mentor.com>
On 7 June 2012 22:59, Carlos O'Donell <carlos_odonell@mentor.com> wrote:
> * If this is a hot path and the allocation size is typically small but may be large, and is known in advance, you can use
> the following pattern:
> {{{
> bool use_alloca = __libc_use_alloca (bufsize);
> struct foo *buf = use_alloca ? alloca (bufsize) : malloc (bufsize);
There should be a check here to ensure that buf is not NULL.
> do_work_with (buf, bufsize);
> if (! use_alloca)
> free (buf);
> }}}
> ?This use of alloca is a memory optimization. ?That is, the above {{{alloca}}} example is almost equivalent to the following:
> {{{
> ? ?struct foo buffer[__MAX_ALLOCA_CUTOFF / sizeof (struct foo)];
> ? ?bool use_auto = bufsize <= sizeof buffer;
> ? ?struct foo *buf = use_auto ? buffer : malloc (bufsize);
> ? ?do_work_with (buf, bufsize);
> ? ?if (! use_auto)
> ? ? ?free (buf);
> }}}
> ?except that the {{{alloca}}} version consumes only the stack space needed, rather than always consuming approximately {{{__MAX_ALLOCA_CUTOFF}}} bytes. Note that this isn't quite equivalent to the previous example because {{{__libc_use_alloca}}} limits alloca to {{{PTHREAD_STACK_MIN/4}}} (which may be bigger than {{{__MAX_ALLOCA_CUTOFF}}}) or {{{<thread stack size>/4}}}, the latter having a maximum bound of {{{__MAX_ALLOCA_CUTOFF}}}.
This is unnecessary and even wrong. This code allocates both, on stack
as well as on heap. That is not what the cutoff selection code above
will do -- you'll have only one of the two. Also, there's never really
a case where all of the __MAX_ALLOCA_CUTOFF is allocated, so the only
'memory optimization' to speak of here is the malloc chunk overhead on
the heap, which isn't much to brag about.
--
Siddhesh Poyarekar
http://siddhesh.in