best way to return (char *)

Henry Spencer henry at utzoo.uucp
Sat Jun 24 03:07:49 AEST 1989


In article <2793 at solo8.cs.vu.nl> maart at cs.vu.nl (Maarten Litmaath) writes:
>\    .	Have the routine malloc() space, and let the caller free() it when
>\	done with the returned pointer.
>
>In general you want to deal with the memory all on the same level.
>It simplifies administration.

Untidy though this approach is, it's often the best -- it alone avoids
setting arbitrary bounds on the size of the returned value.  (Of course,
there are situations where the size of the returned value is inherently
bounded...)  The penalties are some loss of efficiency -- malloc and
free take time -- and a management hassle.

If you want to combine high speed and unbounded returned values and are
willing to commit unspeakable acts to do it :-), have the caller pass in
a buffer (and its size!) which is *usually* big enough, and have the
function return either that buffer or (if it's not large enough) malloced
memory.  This avoids the malloc overhead most of the time and still lets
values be of unlimited size.  It's definitely a nuisance to manage, though.
-- 
NASA is to spaceflight as the  |     Henry Spencer at U of Toronto Zoology
US government is to freedom.   | uunet!attcan!utzoo!henry henry at zoo.toronto.edu



More information about the Comp.lang.c mailing list