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 ;).
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.

For e.g.

int FunctionA()
{
   char* pszLineBuffer = (char*) malloc(1024*sizeof(char));
    …..
  // Program logic
     ….
  free(pszLineBuffer);
  return 1;
}

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 :-

int NewFunctionA()
{
   char* pszLineBuffer = (char*) _alloca(1024*sizeof(char));
    …..
  // Program logic
     ….
  //no need to free szLineBuffer
  return 1;
}

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.


One can also right ask that :-
"_alloca function is deprecated because a more secure version is available.
_malloca : Allocates memory on the stack. This is a version of _alloca with security enhancements."

My Answer to this question is :-
"malloca does not allocates memory from stack always, it will go to heap depending on _ALLOCA_S_THRESHOLD value. Also you need to manage its deallocation flow. _alloca is best suited to be used when you need small chunk of memory but very frequently and if chuck size is not guaranteed to be small _malloca can be used.
One more point _malloca always allocates memory from the heap in DEBUG mode. So you get diffrent behavior in release and debug."

I hope you enjoyed this post.
-Tajendra

NOTE:- I have added hyperlink in accordance to rule, which says :-
"Self-promotion links are permitted within forum signatures provided they do not contradict with any other sitewide rules, such as inappropriate language or content." So is it ok?

My system doesn't have malloca() - so now what?

> One has to keep in mind about allocation size here, as stack overflow exception may occur.
Yeah, with the emphasis on "may", and that's the good side.
The bad side, the OS just shoots your program dead.
The ugly side is there is no stack protection at all, and you merrily trash someone else's memory.

Seems like an interesting quirk of your current OS/Compiler combination rather than anything which is portably useful.

>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.

You missed one: _alloca is specific to the Visual Studio runtime library, and any safe use of it requires one to delve into structured exception handling. Translation: Your code's portability is hosed.

Other implementations support some form of alloca, but experience has taught us that it should be avoided[1]. The stack size is an unknown quantity without hurting portability, and the whole point of dynamic allocation is to handle an unpredictable variation of block sizes. Thus, the very nature of alloca promotes brittle software.

>NOTE:- I have added hyperlink in accordance to rule, which says :-
>"Self-promotion links are permitted within forum signatures provided
>they do not contradict with any other sitewide rules, such as
>inappropriate language or content." So is it ok?

Note that "signature" means the signature feature in the control panel. When you set a signature, that signature is applied to all of your posts. In this case, you've created a "fake" signature by typing what you want into the post itself, so it doesn't fall under the self-promotion clause.

[1] Amazingly enough, C99's VLAs are a language-blessed alloca with all of the same problems. So I guess some people haven't learned their lesson.

Yes very true, above article is specific to Microsoft Visual Studio.
Where we get one way to allocate memory dynamically on stack.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.