当前位置: 代码迷 >> 综合 >> __builtin_return_address(LEVEL)函数解释和运行实战
  详细解决方案

__builtin_return_address(LEVEL)函数解释和运行实战

热度:40   发布时间:2024-02-11 00:15:31.0

      gcc默认不支持__builtin_return_address(LEVEL)的参数为非0。好像只支持参数为0。
1、__builtin_return_address(0)的含义是,得到当前函数返回地址,即此函数被别的函数调用,然后此函数执行完毕后,返回,所谓返回地址就是那时候的地址。
2、__builtin_return_address(1)的含义是,得到当前函数的调用者的返回地址。注意是调用者的返回地址,而不是函数起始地址。

3、实战

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>#define MAX_LEVEL 4
void sigfunc(int signo)
{printf("%s(0): %p\n", __func__, __builtin_return_address(0));exit(1);
}int b()
{printf("%s(0): %p\n", __func__, __builtin_return_address(0));printf("%s(1): %p\n", __func__, __builtin_return_address(1));while(1){sleep(1);}
}int a(int temp)
{temp += 1;printf("%s(0): %p\n", __func__, __builtin_return_address(0));b();return temp;
}int main()
{signal(SIGINT, sigfunc);a(123);return 0;
}

执行后:
a(0): 0x400675
b(0): 0x400653
b(1): 0x400675
^Csigfunc(0): 0x30bda33140

用gdb调试:
gdb e
...
(gdb) l *0x400675
0x400675 is in main (e.c:37).
32    int main()
33    {
34        signal(SIGINT, sigfunc);
35        a(123);
36    
37        return 0;
38    }

 文字部分转载自:__builtin_return_address(LEVEL)函数解释

代码部分转载自:用__builtin_return_address获得程序运行栈情况

  相关解决方案