Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!cs.utexas.edu!tut.cis.ohio-state.edu!snorkelwacker!apple!agate!WEB.berkeley.edu!m100-2ai From: m100-2ai@WEB.berkeley.edu Newsgroups: comp.lang.c Subject: Function returning Structure: How does it work? Keywords: structure, struct Message-ID: <1990May28.215331.29333@agate.berkeley.edu> Date: 28 May 90 21:53:31 GMT Sender: usenet@agate.berkeley.edu (USENET Administrator;;;;ZU44) Reply-To: m100-2ai@WEB.berkeley.edu () Distribution: usa Organization: University of California, Berkeley Lines: 68 Hi everyone. The following seems to be an "easy" question. However, after thinking about it, I find that I don't really understand how it really works... Assume I have the following structure defined... typedef struct STRUCT STRUCT; struct STRUCT { int num; /* Other fields */ }; in ANSI C, I can define a function returning STRUCT, such as the following: STRUCT function(void) { STRUCT structure; structure.num = 0; /* Set other fields as well */ return structure; } 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? For example: boolean is_something(STRUCT s) { return s.num * ....; } And the call: if (is_something(function())) { printf("true."); } will create garbage because the we cannot access the 'structure' returned by function, and since it is allocated on the heap, it won't go away. Essentially, it is garbage. However, what strikes me more is that there seems to be no way you can free that garbage. I can try to do the following: STRUCT *ptr; ptr = &(function()); /* This may, or may not work, depending on */ /* your compiler. */ if (is_something(*ptr)) { printf("true."); } free(ptr); /* Again, may or may not work. */ As a matter of fact, there seems to be NO WAY you can manually free the heap storage claimed by 'structure'. I don't think my assumption about garbage is correct. However, I just can't think of how the C-compiler actually handles it. Can some one please disclaim/confirm what I have said. Or even better, can some one please enlighten me to show me how this is really done. Any help or suggestion is GREATLY appreciated. __ ___ ___ _/' Conrad Wong (cwong@cory.berkeley.edu) / \ __/ \----' \-' c`-o | | / > __/_ / __/_`, _| Imitation is the sincerest form of \__/ \_____\`--\____\ ;/' lack of imagination -- Ghondahrl