I understand the answer given by this very similar question: When is it best to use the stack instead of the heap and vice versa?
But I would like to confirm:
Here is a very simple program:
void update_p(double * p, int size){
//do something to the values refered to by p
}
void test_alloc(int size){
double p[size];
unsigned int i;
for(i=0;i<size;i++)p[i]=(double)i;
update(&p,size);
for(i=0;i<size;i++)printf("%f\n",p[i]);
}
int main(){
test_alloc(5);
return 1;
}
and an alternative version of test_alloc:
void test_alloc(int size){
double * p = calloc(sizeof(double),size);
unsigned int i;
for(i=0;i<size;i++)p[i]=(double)i;
update(p,size);
for(i=0;i<size;i++)printf("%f\n",p[i]);
free(p);
}
It seems to be both version are valid (?). One is using the stack, the other is using heap (?). Are both approach valid? What are their advantages or issues?
If indeed the array is not to be used once exited from test_alloc, is the first approach preferable as not requiring memory management (i.e. forgetting to free the memory) ?
If test_alloc is called massively, is it more time consuming to reserve memory in the heap and might this have an impact on performance?
Would there be any reason to use the second approach?
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.