best way to return (char *)

michael.p.lindner mpl at cbnewsl.ATT.COM
Fri Jun 23 05:51:27 AEST 1989


In article <7800013 at gistdev>, joe at gistdev.UUCP writes:
> Here is a question I haven't seen recently, and I'd like to get opinions from
> the collective wisdom of the group.  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:
	I don't know if I qualify as collective wisdom, but here's my opinion.

>     .	Have the caller pass a (char *) and let the caller worry about
> 	allocating whatever space is needed.
Bad.  In general, the caller knows little about the expected size, so must
pass a large array.  Also, if the thing overflows, the callee has no way of
knowing unless you add args to describe the size, which is ugly.  Even then,
there is no sane thing which can be done on overflow, since the callee doesn't know where the array is coming from.

>     .	Have the routine malloc() space, and let the caller free() it when
> 	done with the returned pointer.
Bad.  Lots of times the caller doesn't need the space malloc'd, and it's
a big pain to remember what to free (so much so that many many people will
forget to free it).

>     .	Have the routine allocate the buffer pointed to by the returned
> 	(char *) as a static.
AND
>     .	Assume it's the caller's problem to strcpy() (or other such) from the
> 	pointer before something else can use the space.
if they need to.  I usually do this, where I can.

Of course, my opinions are my own...

Mike Lindner
attunix!mpl
AT&T Bell Laboratories
190 River Rd.
Summit, NJ 07901



More information about the Comp.lang.c mailing list