Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!cs.utexas.edu!csd4.milw.wisc.edu!mailrus!cornell!uw-beaver!apollo!ulowell!masscomp!ftw From: ftw@masscomp.UUCP (Farrell Woods) Newsgroups: comp.lang.c Subject: Re: best way to return (char *) Message-ID: <1287@masscomp.UUCP> Date: 26 Jun 89 13:45:00 GMT References: <7800013@gistdev> Reply-To: ftw@westford.ccur.com (Farrell Woods) Organization: Concurrent Computer Corporation - Westford, Ma Lines: 42 Approved: news In article <7800013@gistdev> joe@gistdev.UUCP writes: >What is the best way to [construct a string and return a pointer to it] so >that your pointer is sure >to be valid when used? I have seen several approaches to this problem: > . Have the caller pass a (char *) and let the caller worry about > allocating whatever space is needed. You will have to guess how much space you need for the string before you call the function to build it. This is not much different from... > . Have the routine allocate the buffer pointed to by the returned > (char *) as a static. ...except here you make your guess at compile-time instead of run-time. Both of these could violate Henry Spencer's Fifth Commandment. > . Have the routine malloc() space, and let the caller free() it when > done with the returned pointer. I assumed that the knowledge of how much space the string requires is contained within the function building the string. If the knowledge is more global, then the caller could take care malloc/free instead of the callee doing the malloc and the caller doing the free. I guess it depends on whether or not you want to break the malloc/free across two functions. > . Assume it's the caller's problem to strcpy() (or other such) from the > pointer before something else can use the space. Bad assumption. You might get away with it sometimes, but then it also might crash in some unfathomable way. > . Don't worry about it at all -- nothing is going to trash your memory > at the pointed-to address before you can actually use it. This is simply asking for trouble. Can you say "interrupt"? -- Farrell T. Woods Voice: (508) 392-2471 Concurrent Computer Corporation Domain: ftw@masscomp.com 1 Technology Way uucp: {backbones}!masscomp!ftw Westford, MA 01886 OS/2: Half an operating system