Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is alloca different from just creating a local variable?

Tags:

c

unix

I read that there is a funciton called alloca that allocates memory from the stack frame of the current function rather than the heap. The memory is automatically destroyed when the function exits.

What is the point of this, and how is it any different from just crating an array of a structure or a local variable within the function? They would go on the stack and would be destroyed at the end of the function as well.

PS: I saw the other alloca question and it didn't answer how these two things are different :)

like image 402
John Humphreys Avatar asked Aug 31 '11 14:08

John Humphreys


1 Answers

When you use alloca, you get to specify how many bytes you want at run time. With a local variable, the amount is fixed at compile time. Note that alloca predates C's variable-length arrays.

like image 179
Rob Kennedy Avatar answered Oct 04 '22 21:10

Rob Kennedy