The question of allocation in stack (or) heap is dependent on the following parameters:
The scope and life time in which you want the variable to be available: Say in your program if you need to use members of the array of double after
test_alloc
inmain
, you should go for dynamic allocation .The size of your stack: Say you are using the
test_alloc
function in a context of a thread which has a stack of 4K, and your array size which in in turn dependent on thesize
variable accounts to 1K, then stack allocation is not advisable, you should go for dynamic allocation.Complexity of code: While using dynamic allocations, enusre to take care of avoiding memory leaks, dangling pointers etc. This adds some amount of complexity to the code and are more prone to bugs.
The frequency of allocation: Calling
malloc
andfree
in a loop may have lesser performance. This point is based on the fact that allocation in stack is just the matter of offseting theSP
, on contrary while allocation in heap needs some more book keeping.