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.
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