By Darryl Gove-Oracle on May 22, 2008
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.