Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!rutgers!att!cbnewsl!mpl From: mpl@cbnewsl.ATT.COM (michael.p.lindner) Newsgroups: comp.lang.c Subject: Re: best way to return (char *) Summary: several ways Message-ID: <894@cbnewsl.ATT.COM> Date: 22 Jun 89 19:51:27 GMT References: <7800013@gistdev> Organization: AT&T Bell Laboratories Lines: 35 In article <7800013@gistdev>, joe@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