Author |
Message |
grazzhoppa Novice
Joined: Jan 03 2007 Posts: 29 Offline
|
Posted: 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) {
StructReturn stack_struct;
return stack_struct;
/* C compiler will create a copy identical to "stack_struct" and automatically allocate memory on the stack of the calling function for this copy, no?*/
} |
|
Back to top |
|
|
Bak ?ls -s 0 in
Age:25 Gender: Joined: Jun 11 2004 Posts: 1826 Location: USA Offline
|
Posted: 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. _________________ SubSpace Discretion: A Third Generation SubSpace Client |
|
Back to top |
|
|
grazzhoppa Novice
Joined: Jan 03 2007 Posts: 29 Offline
|
Posted: 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) {AStruct *malloced_AStruct = (AStruct*) malloc( sizeof(AStruct) );
return *malloced_AStruct; }
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. |
|
Back to top |
|
|
Bak ?ls -s 0 in
Age:25 Gender: Joined: Jun 11 2004 Posts: 1826 Location: USA Offline
|
Posted: 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. |
|
Back to top |
|
|
|