Darryl Gove's blog

Thursday May 22, 2008

Reserving temporary memory using alloca

There are occasions where it's useful to allocate a small temporary working area for the duration of a call to a routine - for example to hold an array. One way of doing this is to use malloc and free:

void f(int a)
{
  int* array=(int*)malloc(sizeof(int)*a);
  ...
  free(array);
}

Obviously the use of malloc and free does incur some overhead, and which is undesirable, particularly if this is a performance critical routine.

An alternative approach is to use alloca which allocates memory on the stack, here's the man page. Being on the stack, the memory is 'freed' when the routine exits. Well, the memory isn't allocated, so it's not really freed, but accesses to the memory once the routine exits are not valid - you'll be accessing data either beyond the stack, or in the stack frame of another routine. Neither situation is likely to be good.

The equivalent code is:

#include 

void f(int a)
{
  int* array=(int*)alloca(sizeof(int)*a);
  ...
}

For routines which do require temporary storage, this can be a much faster way of allocating it.

Comments:

Note that with C99 you could use variable length arrays instead, e.g.

void f(int a)
{
int array[a];
}

Posted by Christof Meerwald on May 22, 2008 at 02:36 PM PDT #

Yes. Frank Hofmann also talks about this option:
http://blogs.sun.com/ambiguous/entry/more_on_alloca

The underlying mechanism for alloca and variable length arrays is the same - they both shift the stack pointer.

Posted by Darryl Gove on May 22, 2008 at 02:51 PM PDT #

Post a Comment:
Comments are closed for this entry.

Calendar

Search this blog

About

Solaris Application Programming

Book resources

The Developer's Edge

Book resources

OpenSPARC Internals

Book resources

Recent entries

Custom search

Tag cloud

book cmt communityone compiler cooltools cpu2006 dtrace gcc libraries linker multithreading openmp opensolaris opensparc optimisation optimization parallelisation parallelization performance performanceanalyzer programming secondlife solaris solarisapplicationprogramming sparc spot sunstudio ultrasparc ultrasparct2 x86

Links

Webcasts

Articles

Presentations

Interesting docs

Navigation

Referers

Feeds