Function returning Structure: How does it work?

Henry Spencer henry at utzoo.uucp
Wed May 30 01:47:36 AEST 1990


In article <1990May28.215331.29333 at agate.berkeley.edu> m100-2ai at WEB.berkeley.edu () writes:
>...in ANSI C, I can define a function returning STRUCT...
>Now, it seems that the storage space for 'structure' has to be allocated
>on the heap (not on stack).  However, wouldn't this create a lot of
>garbages you won't be able to free? ...

It would, but that's not how it's done.  Returning a struct value *is*
tricky, and compilers use a variety of methods, but allocating heap space
is generally not acceptable, and allocating space that doesn't get freed
is definitely not acceptable.  The best method is for the caller, knowing
it's calling a struct-valued function, to allocate some space for the
return value, and either do this in a known place or else pass an extra
parameter which is a pointer to the space.  Then the called function just
puts the return value there.  This does fall down badly if the user does
not bother to declare that he's calling a struct-valued function, but
that comes under the heading of "if you lie to the compiler, it will get
its revenge".
-- 
As a user I'll take speed over|     Henry Spencer at U of Toronto Zoology
features any day. -A.Tanenbaum| uunet!attcan!utzoo!henry henry at zoo.toronto.edu



More information about the Comp.lang.c mailing list