Allocating memory on stack.

We’ve done memory allocation on heap, but ever thought of doing this on stack! Well why do we need to allocate memory on stack if we have sufficient heap space left with us.

A function called _alloca is provided just for this purpose.

Reasons why I use _alloca is, because the memory allocated is small but size varies and I’ve got multiple return points from a function, so I don’t have to keep freeing this allocated memory from every such return point.

This has been taken from MSDN:

Another C runtime function, _alloca,  should be used instead of the heap allocator
when the item to be allocated is of function scope, requires only short-term memory
use, and its size can vary. The _alloca function simply extends the function's stack
frame, so it is very fast. When the function returns, the allocation evaporates.

Well this is cool but do you have any live usage of this function? Yes I do, our common UNICODE to ANSI and ANSI to UNICODE conversion functions use this function. A2W and W2A use this function internally to allocate some temporary space for holding converted strings.

Note that you should not return such a buffer from a function, since the buffer will be destroyed when returning from the function, treat the buffer allocated by this function as a local variable. Also do not free such a buffer!

Caveat for this function is that it can cause a stack overflow exception, iif stack runs out of space which shouldn’t happen often unless with some heavy recursive stuff going on.

Appreciate your comments...