Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!batcomputer!caen!uakari.primate.wisc.edu!aplcen!boingo.med.jhu.edu!haven!adm!smoke!gwyn From: gwyn@smoke.brl.mil (Doug Gwyn) Newsgroups: comp.lang.c Subject: Re: do I need to allocate space twice? Message-ID: <15637@smoke.brl.mil> Date: 30 Mar 91 14:21:37 GMT References: <8338@umd5.umd.edu> Organization: U.S. Army Ballistic Research Laboratory, APG, MD. Lines: 23 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.