Newsgroups: comp.lang.c Path: utzoo!henry From: henry@utzoo.uucp (Henry Spencer) Subject: Re: Function returning Structure: How does it work? Message-ID: <1990May29.154736.18459@utzoo.uucp> Organization: U of Toronto Zoology References: <1990May28.215331.29333@agate.berkeley.edu> Date: Tue, 29 May 90 15:47:36 GMT In article <1990May28.215331.29333@agate.berkeley.edu> m100-2ai@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@zoo.toronto.edu