Darryl Gove's blog

Thursday May 22, 2008

Alloca internals

Temporary memory allocated using alloca is allocated on the stack. Stacks start at the top of memory and grow downwards (whereas heap grows upwards, low memory to high memory). There are two pointers that help the processor determine where the stack is, the frame pointer and the stack pointer. The usuak situation is something like this:

Frame pointer -> top of stack
                 variables
Stack pointer -> bottom of stack

When a new routine is called and allocates local variables the resulting stack looks like:

              -> top of stack
                 variables
Frame pointer -> old bottom of stack
                 variables
Stack pointer -> bottom of stack

The old stack pointer becomes the new frame pointer, a new amount of space is reserved on the stack for the local variables, and then the stack pointer points to the new bottom of the stack.

When alloca is called, the application reserves more memory on the stack. This is basically a case of moving the stack pointer downwards - like this:

              -> top of stack
                 variables
Frame pointer -> old bottom of stack
                 variables
                 [alloca'd memory]
Stack pointer -> bottom of stack

So rather than the overhead of calling new and free, the memory gets allocated with the cost of very few instructions - often just two. One instruction to calculate the base address of the allocated memory, and one instruction to move the stack pointer.

Comments:

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