Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!iuvax!uxc.cso.uiuc.edu!uxc.cso.uiuc.edu!gistdev!joe From: joe@gistdev.UUCP Newsgroups: comp.lang.c Subject: best way to return (char *) Message-ID: <7800013@gistdev> Date: 20 Jun 89 13:42:00 GMT Lines: 32 Nf-ID: #N:gistdev:7800013:000:1624 Nf-From: gistdev.UUCP!joe Jun 20 08:42:00 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@uxc.cso.uiuc.edu (217) 352-1165 | UUCP : {uunet,pur-ee,convex}!uiucuxc!gistdev!joe -------------------------------------------------------------------------------