best way to return (char *)

joe at gistdev.UUCP joe at gistdev.UUCP
Tue Jun 20 23:42:00 AEST 1989


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:

    .	Have the caller pass a (char *) and let the caller worry about
	allocating whatever space is needed.

    .	Have the routine malloc() space, and let the caller free() it when
	done with the returned pointer.

    .	Have the routine allocate the buffer pointed to by the returned
	(char *) as a static.

    .	Assume it's the caller's problem to strcpy() (or other such) from the
	pointer before something else can use the space.

    .	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.

I'm sure there are other approaches, but these were the ones I could think of
off the top of my head.  In general, how _should_ this be done to be safest?

-------------------------------------------------------------------------------
Joe Brownlee       | Captain, please -- not in front of the Klingons...
GIST, Inc.         |                                -- Mr. Spock, Star Trek V
1800 Woodfield Dr. | Pay attention to what I say, and you might start a trend.
Savoy, IL 61874	   | ARPANET: joe%gistdev at uxc.cso.uiuc.edu
(217) 352-1165	   | UUCP   : {uunet,pur-ee,convex}!uiucuxc!gistdev!joe
-------------------------------------------------------------------------------



More information about the Comp.lang.c mailing list