Server Help

Non-Subspace Related Coding - ANSI C: Returning struct variable on the stack from a func

grazzhoppa - Fri Nov 30, 2007 8:21 pm
Post subject: ANSI C: Returning struct variable on the stack from a func
I was under the impression that C will create a copy of the returned struct so that memory corruption is not being risked. Is this true?

I was told that using the returned struct risks memory corruption since the struct being returned by AFunction() was created on the stack within the function and hence it's memory area gets marked "available" to the OS when the function exists.

typedef struct _whatever {

} StructReturn;

StructReturn AFunction(void) {

}
Bak - Fri Nov 30, 2007 9:05 pm
Post subject:
yeah it'll create a copy... whoever told you memory will be corrupted probably meant if you returned a pointer to a struct declared on the stack inside the function.
grazzhoppa - Sat Dec 01, 2007 11:34 am
Post subject:
No, he was explicit about returning a regular struct created on the stack within the function.

The person recommended 1)creating a pointer, 2)using malloc(), 3)then returning the dereferenced pointer such as this:

AStruct AFunction(void) {}

But, in the context of what we were talking about, this would've been a memory leak because the calling function doesn't free() anything.
Bak - Sat Dec 01, 2007 11:53 am
Post subject:
yeah.

in general people discourage returning structs as it does create a copy which is a bit wasteful for large structs. A better way to do it is to pass in a pointer to the struct as an argument, then modify it in the function.
All times are -5 GMT
View topic
Powered by phpBB 2.0 .0.11 © 2001 phpBB Group