How does returning values from a function work?

后端 未结 8 1664
被撕碎了的回忆
被撕碎了的回忆 2021-01-05 12:16

I recently had a serious bug, where I forgot to return a value in a function. The problem was that even though nothing was returned it worked fine under Linux/Windows and on

8条回答
  •  南方客
    南方客 (楼主)
    2021-01-05 12:35

    There are two major ways for a compiler to return a value:

    1. Put a value in a register before returning, and
    2. Have the caller pass a block of stack memory for the return value, and write the value into that block [more info]

    The #1 is usually used with anything that fits into a register; #2 is for everything else (large structs, arrays, et cetera).

    In your case, the compiler uses #1 both for the return of new and for the return of your function. On Linux and Windows, the compiler did not perform any value-distorting operations on the register with the returned value between writing it into the pointer variable and returning from your function; on Mac, it did. Hence the difference in the results that you see: in the first case, the left-over value in the return register happened to co-inside with the value that you wanted to return anyway.

提交回复
热议问题