best way to return (char *)
Farrell Woods
ftw at masscomp.UUCP
Mon Jun 26 23:45:00 AEST 1989
In article <7800013 at gistdev> joe at gistdev.UUCP writes:
>What is the best way to [construct a string and return a pointer to it] 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.
You will have to guess how much space you need for the string before you
call the function to build it. This is not much different from...
> . Have the routine allocate the buffer pointed to by the returned
> (char *) as a static.
...except here you make your guess at compile-time instead of run-time.
Both of these could violate Henry Spencer's Fifth Commandment.
> . Have the routine malloc() space, and let the caller free() it when
> done with the returned pointer.
I assumed that the knowledge of how much space the string requires is
contained within the function building the string. If the knowledge is more
global, then the caller could take care malloc/free instead of the callee
doing the malloc and the caller doing the free. I guess it depends on
whether or not you want to break the malloc/free across two functions.
> . Assume it's the caller's problem to strcpy() (or other such) from the
> pointer before something else can use the space.
Bad assumption. You might get away with it sometimes, but then it also might
crash in some unfathomable way.
> . 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.
This is simply asking for trouble. Can you say "interrupt"?
--
Farrell T. Woods Voice: (508) 392-2471
Concurrent Computer Corporation Domain: ftw at masscomp.com
1 Technology Way uucp: {backbones}!masscomp!ftw
Westford, MA 01886 OS/2: Half an operating system
More information about the Comp.lang.c
mailing list