问题
I want to get the return address of the caller function. I'm using __builtin_return_address()
funtion, but if I give index value greater than 0 it is returning NULL
.
Please help me with this or tell me any other function to get the same.
回答1:
See this answer to a related question.
__builtin_return_address is GCC and processor specific (also available in some versions of Clang on some processors with some -lack of- optimizations), and documented as
On some machines it may be impossible to determine the return address of any function other than the current one
The compiler might optimize a function (e.g. when it is compiled with -fomit-frame-pointer
, or for tail-calls, or by function inlining) without the relevant information.
So probably you are getting NULL
because the information is not available!
回答2:
In addition to compiler optimisation reasons (which IMO is the most likely reason for the issue you're facing), the GCC documentation states quite plainly:
Calling this function with a nonzero argument can have unpredictable effects, including crashing the calling program. As a result, calls that are considered unsafe are diagnosed when the
-Wframe-address
option is in effect. Such calls should only be made in debugging situations.
As Basile said, since it's a compiler builtin (read: very processor specific and a bad idea to use) the behaviour is exceptionally loosely defined (as it is not required by any standards and does not have to make any guarantees).
Just use backtrace(3), it's POSIX-compliant and doesn't rely on compiler builtins.
来源:https://stackoverflow.com/questions/26888027/builtin-return-address-returns-null-for-index-0