Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.milw.wisc.edu!lll-winken!uunet!mcvax!hp4nl!botter!star.cs.vu.nl!maart From: maart@cs.vu.nl (Maarten Litmaath) Newsgroups: comp.lang.c Subject: Re: best way to return (char *) Message-ID: <2793@solo8.cs.vu.nl> Date: 22 Jun 89 19:26:05 GMT References: <7800013@gistdev> Organization: V.U. Informatica, Amsterdam, the Netherlands Lines: 39 joe@gistdev.UUCP writes: \... Suppose I am writing a function that is \going to construct a character string, and is going to return a pointer to \that string. What is the best way to do this 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. That's the way, I tell thee! But who am I, since this macro business? \ . Have the routine malloc() space, and let the caller free() it when \ done with the returned pointer. In general you want to deal with the memory all on the same level. It simplifies administration. \ . Have the routine allocate the buffer pointed to by the returned \ (char *) as a static. In general: NO! Consider routines like getpwent(): if you want to keep the info, you have to copy it yourself, doubling the work. I say: if the caller wants a static buffer, let HIM do the arrangements. He's quite competent. \ . Assume it's the caller's problem to strcpy() (or other such) from the \ pointer before something else can use the space. That's precisely what you want to avoid: HOW can you be SURE some other (low-level) routine doesn't invoke the function too, thereby destroying YOUR data? Consider something like printf() invoking malloc(). (I KNOW this isn't a very good example.) \ . 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. Huh? -- "I HATE arbitrary limits, especially when |Maarten Litmaath @ VU Amsterdam: they're small." (Stephen Savitzky) |maart@cs.vu.nl, mcvax!botter!maart