best way to return (char *)

Maarten Litmaath maart at cs.vu.nl
Fri Jun 23 05:26:05 AEST 1989


joe at 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 at cs.vu.nl, mcvax!botter!maart



More information about the Comp.lang.c mailing list