[comp.lang.c] Re^2: best way to return

maart@cs.vu.nl (Maarten Litmaath) (06/27/89)

bill@twwells.com (T. William Wells) writes:
\In article <2793@solo8.cs.vu.nl> maart@cs.vu.nl (Maarten Litmaath) writes:
\: 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.
\
\No. In this kind of thing, it makes life much more complex. The
\fundamental problem is this: if the caller makes the allocation
\decisions, the caller may well be wrong. That involves complex error
\recovery, or it is equivalent to fixed buffer sizes (as far as the
\called routine is concerned).

Allright. In THIS particular case it might be better to let the called
function allocate the space via malloc(). I only wanted to point out I'm
SICK AND TIRED of static buffers in functions like getpwent(), that is
routines which can be expected to get called in a row.
Recall that I said `in general'? The programmer is inclined to forget to
free() the allocated space.
On the other side: if the caller supplies a buffer, an extra parameter
specifying the size of this buffer isn't that odd - remember strncpy()?
-- 
"I HATE arbitrary limits, especially when |Maarten Litmaath @ VU Amsterdam:
   they're small."  (Stephen Savitzky)    |maart@cs.vu.nl, mcvax!botter!maart