Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does C return a structure? [duplicate]

(gdb) disas func
Dump of assembler code for function func:
0x00000000004004b8 <func+0>:    push   %rbp
0x00000000004004b9 <func+1>:    mov    %rsp,%rbp
0x00000000004004bc <func+4>:    movl   $0x64,0xfffffffffffffff0(%rbp)
0x00000000004004c3 <func+11>:   movb   $0x61,0xfffffffffffffff4(%rbp)
0x00000000004004c7 <func+15>:   mov    0xfffffffffffffff0(%rbp),%rax
0x00000000004004cb <func+19>:   leaveq
0x00000000004004cc <func+20>:   retq
End of assembler dump.


t_test func()
{
    t_test t;
    t.i = 100;
    t.c = 'a';
    return t;
}

So it seems it's returning the local variable t,but is this kind of job guaranteed to work, isn't it supposed not to refer to any local variables when return??

like image 709
new_perl Avatar asked Jul 18 '11 09:07

new_perl


People also ask

Can C return a structure?

Now, functions in C can return the struct similar to the built-in data types. In the following example code, we implemented a clearMyStruct function that takes a pointer to the MyStruct object and returns the same object by value.

Does C Copy structs?

In C/C++, we can assign a struct (or class in C++ only) variable to another variable of same type. When we assign a struct variable to another, all members of the variable are copied to the other struct variable.

How are structure passing and returning implemented in C?

Q: How are structure passing and returning implemented? A: When structures are passed as arguments to functions, the entire structure is typically pushed on the stack, using as many words as are required. (Programmers often choose to use pointers to structures instead, precisely to avoid this overhead.)

Can struct be a return type?

Return struct from a functionThe function returns a structure of type struct student . The returned structure is displayed from the main() function. Notice that, the return type of getInformation() is also struct student .


1 Answers

In my experience, there is no standard way how C returns a structure. To be able to pass a struct, the compiler usually (invisibly to the user) passes a pointer to the struct, to which the function can copy the contents. How this pointer is passed (first or last on stack) is implementation dependent. Some compilers, like 32 bit MSVC++ return small structures in registers like EAX and EDX. Apparently, GCC returns such a struct in RAX, in 64 bit mode.

But, once again, there is no standard way how this is done. That is no problem when the rest of the code using a function is also compiled by the same compiler, but it is a problem if the function is an exported function of a DLL or a lib. I have been bitten by this a few times, when using such functions from a different language (Delphi) or from C with a different compiler. See this link too.

like image 119
Rudy Velthuis Avatar answered Sep 21 '22 17:09

Rudy Velthuis