[comp.lang.c] Question about return values of type struct

u-tholly@wasatch.utah.edu (Troy Holly) (07/29/89)

What happens when a procedure returns an auto variable of type struct?
The variable in question is declared in the procedure that returns it.
Am I right in thinking that auto variables "exist" on the stack only
during the time that the procedure is active?  The code in question
looks something like this:

type def struct {
	double *ptr1;
	double *ptr2;
	int n;
	int m;
} mystruct;

mystruct copyfoo(foo1) mystruct foo1; {
	
	mystruct foo2;
	int i;
	
	foo2.ptr1 = malloc( m * sizeof(double) );
	for ( i = 0; i < foo1.m; i++ )
		foo2.ptr1[i] = foo1.ptr1[i];
	.
	.
	.
	return ( foo2 );
}

main () {

	mystruct foo3, foo4;

	.
	.	(assign foo4 some values)
	.
	foo3 = copyfoo(foo4);
	.
	.
	.
}

I am worried about this code.  I have more or less inherited it.  Does
the assignment to foo3 in main() need to be done with pointers, i.e.,  
should copyfoo() return a pointer to struct instead of a struct?  Like
I said above, I am worried that the struct in copyfoo() that is returned
will be overwritten on the stack.

Thanks in advance,

Troy -


	
	

Roy.Browning@f506.n106.z1.fidonet.org (Roy Browning) (07/31/89)

 > From: u-tholly@wasatch.utah.edu (Troy Holly)
 > Date: 29 Jul 89 04:34:41 GMT
 > Organization: University of Utah CS Dept
 > Message-ID: <2264@wasatch.utah.edu>

 > mystruct copyfoo(foo1) mystruct foo1; {
 >         mystruct foo2;
 >         return ( foo2 );

 > main () {
 >         mystruct foo3, foo4;
 >         foo3 = copyfoo(foo4);

 > I am worried about this code.  I have more or less inherited it.  Does
 > the assignment to foo3 in main() need to be done with pointers, i.e.,  
 > should copyfoo() return a pointer to struct instead of a struct?  Like

Troy:

        Function "copyfoo()" is indeed returning a structure and that structure is being COPIED to "foo3" in the main function.  Thus after the assignment you will be accessing the structure defined in "main()" not in "copyfoo()".  Do an assembly dump if you wish to confirm that the structure is copied.

                                 Intermediate 'C'eer,

                                   Roy Browning

Rik.Stevans@f226.n105.z1.FIDONET.ORG (Rik Stevans) (08/20/89)

--  
Rik Stevans - via FidoNet node 1:105/14
	    UUCP: ...!{uunet!oresoft, tektronix!reed}!busker!226!Rik.Stevans
	    ARPA: Rik.Stevans@f226.n105.z1.FIDONET.ORG