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?