Dynamic Memory Allocation But using STACK

Posted: May 2, 2016 in Softwares
Tags: , , , , ,


First let discover how to use it;

voidalloca(size_t size)

So its usage is like malloc, except that it allocates in a stack portion of memory, not the heap which means, allocating a block with alloca is an explicit action; you can allocate as many blocks as you wish, and compute the size at run time. But all the blocks are freed when you exit the function that alloca was called from, just as if they were automatic variables declared in that function. There is no way to free the space explicitly.

  • Pros:
  1. Using alloca wastes little space than malloc and is very fast
  2. alloca does not cause memory fragmentation
  3. Automatically free the space allocated with alloca when they exit through the function that called alloca, no memory leakage.
  • Cons:
  1. If you try to allocate more memory than the machine can provide, you don’t get NULL pointer as a return value, you’ll get a stack overflow.
  2. It is less portable than malloc, not supported by all compilers.
  1. Don’t return with its pointer
  2. Don’t store its pointer to global variable of structure allocated in heap or …
  3. Don’t use it inside arguments of function call

Leave a Comment about this:

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: