Function returning Structure: How does it work?

m100-2ai at WEB.berkeley.edu m100-2ai at WEB.berkeley.edu
Tue May 29 07:53:31 AEST 1990


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 at cory.berkeley.edu)
 /  \     __/   \----'   \-' c`-o
|    |   /  > __/_   / __/_`,  _|     Imitation is the sincerest form of
     \__/   \_____\`--\____\ ;/'       lack of imagination -- Ghondahrl



More information about the Comp.lang.c mailing list