4

I've seen many functions that return a struct in C without memory allocation or pointers, and I thought there's nothing wrong about it. However, I just learned that after compilation, a function will return a value using %rax or %eax register, depending on the architecture. Then, if the struct is bigger then 64 or 32 bits, wouldn't it be impossible to fit the struct in register? What am I missing?

machine_1
  • 4,266
  • 2
  • 21
  • 42
cobaltblue
  • 89
  • 8
  • 4
    You are missing reading the calling convention documentation (ABI). It will tell you how to return stuff. Large structures are typically returned using a hidden pointer passed in as first argument. – Jester Mar 20 '18 at 16:27
  • 2
    To return structures by value is widely recognized as bad practice... so just don't do it? – Lundin Mar 20 '18 at 16:30
  • 3
    If you want to see what's going on under the hood, well you need to look under the hood, that is you need to look at the assembly code generated by the compiler. – Jabberwocky Mar 20 '18 at 16:30
  • Just made a function and tried objdump. It seems function directly stores value in the stack.. so returning value is more than just storing value in a register. Thanks for you answers :) – cobaltblue Mar 20 '18 at 16:47
  • Fun fact: The x86-64 System V ABI packs structs into `rdx:rax` if they're 16 bytes or smaller. (Without padding. So if the real struct does have padding, the caller has to unpack with shifts before even storing to memory, not just before using; maybe not the best design, unfortunately. :/ But try to avoid padding anyway.) – Peter Cordes Mar 20 '18 at 22:29

0 Answers0