best way to return (char *)

Alastair Dallas awd at dbase.UUCP
Wed Jun 28 09:39:36 AEST 1989


I have two favorite "places to store the characters" from the list
given by the original poster.

1) Let the caller allocate storage and pass a pointer is a sure winner.
	void func(char *)

2) Let the function malloc() storage which the caller then frees.
	char *func()

Other options are just too dangerous on a large multi-programmer project,
in my opinion.  There are some pitfalls even with these two.  Many 
functions are written such that a pointer is expected (#1), but a 0
passed in its place implies method #2.  Thus, #1 becomes:

	char *func(char *)

where the original argument is returned if != 0.  The problem here
is that some callers will malloc() and others will pass 0 and both
results should be freed.  However, still other callers will pass
static and automatic arrays, which must not be freed.  And, finally,
how can the function protect itself from "bad" (.e.g <0) pointers?
At least method #2 keeps the function in control.

/alastair/



More information about the Comp.lang.c mailing list