[comp.lang.c] do I need to allocate space twice?

jjk@jupiter.astro.umd.edu (Jim Klavetter) (03/30/91)

I have a function which returns a pointer of type double.  This is
really an "array".  Should the main program or the function allocate
the space?  Does it matter?  Certainly, I don't need to allocate space
twice, right?

To make this clear, here is a simple example:  add two arrays:

double *addarray(a, b, n)
double *a, *b;
int n;
{
	int i;
	double *result;

	for(i=0; i<n; i++)
		result[i]=a[i]+b[i];
	return(result);
}

with the main program having the fragment:

double *sum, *addarray();
...
sum=addarray(x, y, num);
...

The question is where do I allocate the storage for sum?  It seems to
me that if I do it in the function, then I can just return the pointer
and that is all, since the space will be allocated.  Is this correct?
As a followup, if I ever want to free the space, and it is true that I
allocate it in the function, then can I free the pointer from main?

As an aside, don't worry about code optomization or even bugs:  I just
made it up on the fly and I use it to get the idea across.  If I've
made any conceptual mistakes, on the other hand, please let me know?

jjk@astro.umd.edu also for Athabasca and Reudi
Jim Klavetter
Astronomy
UMD
College Park, MD  20742

gwyn@smoke.brl.mil (Doug Gwyn) (03/30/91)

In article <8338@umd5.umd.edu> jjk@astro.umd.edu (Jim Klavetter) writes:
>The question is where do I allocate the storage for sum?  It seems to
>me that if I do it in the function, then I can just return the pointer
>and that is all, since the space will be allocated.  Is this correct?

Wherever the allocation is done, it must occur BEFORE the first
assignment using the `result' pointer.

There are several methods of allocating storage.  If you let the
function do it, there are three possibilities:
	(1) Use an auto variable for the array (NOT for a pointer).
	This is wrong, since the auto storage becomes invalid when the
	function returns.
	(2) Use a static variable for the array.  This works, but has
	the drawback that the data is clobbered by the next call to
	the function, perhaps before you have finished using the first
	result, which would cause errors.
	(3) Use malloc() to allocate storage.  This works, but the
	application has to keep track of the storage and free it when
	it is through using the result, or else you could eventually
	run out of memory.
It is simpler to have the caller allocate the storage and pass a
pointer to it as another argument to the function.