This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Policy: alloca vs. malloc?


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


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]