do I need to allocate space twice?

Doug Gwyn gwyn at smoke.brl.mil
Sun Mar 31 00:21:37 AEST 1991


In article <8338 at umd5.umd.edu> jjk at 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.



More information about the Comp.lang.c mailing list