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 07:36 AM 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 07:51 AM PDT #

Post a Comment:
Comments are closed for this entry.
About

Darryl Gove is a senior engineer in the Solaris Studio team, working on optimising applications and benchmarks for current and future processors. He is also the author of the books:
Multicore Application Programming
Solaris Application Programming
The Developer's Edge

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
5
6
8
9
10
12
13
14
15
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today
Bookmarks
The Developer's Edge
Solaris Application Programming
Publications
Webcasts
Presentations
OpenSPARC Book
Multicore Application Programming
Docs