I read some time back that memory operation on stack is much faster than heap. With this
information the first thing came into my mind was that if we get a way to allocate memory
dynamically on stack it would surely help us to optimize memory operation cost. I started
searching for it and finally I found one such way J.
Before going into its detail let’s take a look at dynamic memory allocation on heap.
Generally when it comes to dynamic memory allocation new/malloc the well known calls
Comes into mind. They help us to dynamically allocate memory on the heap.
char* pszLineBuffer = (char*) malloc(1024*sizeof(char));
// Program logic
Above code would allocate 1024 bytes on heap dynamically. After the complete use of variable szLineBuffer, we
need to free memory also (free/delete can be used for it). So, one has to keep track of deallocation call,
else memory leak will get introduced.
Now coming back to our question, is there any way by which we can allocate memory dynamically on stack.
So the answer is yes. We can allocate variable length space dynamically on stack memory by using function
_alloca. This function allocates memory from the program stack. It simply takes number of bytes to be allocated and
return void* to the allocated space just as malloc call. This allocated memory will be freed automatically on function exit.
So it need not to be freed explicitly. One has to keep in mind about allocation size here, as stack overflow exception may
occur. Stack overflow exception handling can be used for such calls. In case of stack overflow exception one can use
_resetstkoflw() to restore it back.
So our new code with _alloca would be :-
char* pszLineBuffer = (char*) _alloca(1024*sizeof(char));
// Program logic
//no need to free szLineBuffer
Now let’s check out what will be the advantage of _alloca over new/malloc :-
1) We have saved overhead of new/malloc.
As _alloca() got very little overhead of allocating memory on stack.
2) No need to free memory explicitly. So, deallocation cost will be zero.
3) If function like FunctionA() got multiple time in your program it may cause heap memory fragmentation on a long run,
Which would be saved with NewFunctionA() as stack memory never goes fragmented.
Now let’s check out what will be the disadvantage of _alloca over new/malloc :-
1) One has to be cautious while using alloca for huge blocks.
2) Its scope is limited to a function call.
3) As stack overflow is not a standard C++ exception, one hast to use structured exception handling for it.
I hope you enjoyed this post.