Reputation: 18754
I was revising C and came across to alloca/free functions which is described as allocating storage on a stack like space. Is this same as the malloc/free ? or this is something different ? Thanks.
Upvotes: 12
Views: 11045
Reputation: 12270
Adding some extra information to an old answer.
malloc()
can be used for few reason, some of them are
But, one extra work that gets added with malloc()
is we have to explicitly free()
the allocated memory.
So, in order to use only the Dynamic memory allocation feature, and to avoid the overhead of free()
, one can use alloca()
in their program. This is made possible because memory is allocated on the stack (as mentioned by other answers) when alloca()
is used.
Upvotes: 1
Reputation: 4366
malloc
, calloc
and realloc
functions allocate space on the heap.
free
function "frees" space previously allocated by these functions.
Upvotes: 3
Reputation: 613202
I think you mean alloca
which is used to allocate memory on the stack. And yes, this is different from malloc
and free
which allocate on the heap.
Don't attempt to free memory allocated with alloca
because it is automatically freed when the function that calls alloca
returns to its caller.
Using alloca
and/or C99 variable length arrays can be a risky business because you can readily overflow the stack if you use these tools imprudently.
Upvotes: 24