打印栈深度

#define read_esp() ({ \
         unsigned int __dummy; \
         __asm__( \
                 "movl %%esp,%0\n\t" \
                 :"=r" (__dummy)); \
         __dummy; \
 })
 
 
current stack size:
(__u32)current_thread_info() + 0x2000 - read_esp()
在程序中打印函数调用的大小或获取当前线程的大小,是调试溢出、内存泄漏等问题的重要手段。以下是几种常见平台和语言下的实现方式: ### 获取当前线程的调用大小 在 Linux 系统中,可以使用 `backtrace` 函数来获取当前线程的调用信息,并通过返回值确定深度。该函数将当前调用的返回地址写入指定的指针数组中,返回实际写入的地址数量[^3]。 示例代码如下: ```c #include <execinfo.h> #include <stdio.h> void print_call_stack_size() { void* callStack[32]; // 定义一个指针数组用于存储调用地址 int frameCount = backtrace(callStack, 32); // 获取调用的帧数 printf("Current call stack size: %d\n", frameCount); } void func3() { print_call_stack_size(); } void func2() { func3(); } void func1() { func2(); } int main() { func1(); return 0; } ``` 上述代码中,`backtrace` 函数用于获取当前调用的大小并打印输出。这种方法适用于调试深度问题,尤其是在排查递归调用或无限循环导致的溢出情况。 ### 获取当前线程的大小(总容量) 获取当前线程的大小通常需要依赖操作系统提供的 API 或系统调用。在 Linux 中,可以通过 `pthread_attr_getstack` 函数获取线程的大小[^3]。 示例代码如下: ```c #include <pthread.h> #include <stdio.h> #include <stdlib.h> void get_thread_stack_size() { pthread_t thread = pthread_self(); pthread_attr_t attr; size_t stack_size; // 初始化线程属性 pthread_getattr_np(thread, &attr); // 获取大小 pthread_attr_getstack(&attr, NULL, &stack_size); printf("Current thread's stack size: %zu bytes\n", stack_size); // 释放线程属性资源 pthread_attr_destroy(&attr); } int main() { get_thread_stack_size(); return 0; } ``` 该代码通过 `pthread_getattr_np` 和 `pthread_attr_getstack` 获取当前线程的大小,并输出结果。这对于检测空间是否被耗尽、是否存在溢出风险具有重要意义。 ### Windows 平台的信息获取 在 Windows 平台上,可以通过 `StackWalk64` 函数获取调用信息,该函数属于 DbgHelp 库,能够遍历当前线程的调用并获取返回地址[^2]。 示例代码如下: ```cpp #include <windows.h> #include <dbghelp.h> #include <iostream> void print_call_stack_size() { void* stack[100]; unsigned short frames = CaptureStackBackTrace(0, 100, stack, NULL); std::cout << "Current call stack size: " << frames << std::endl; } void func3() { print_call_stack_size(); } void func2() { func3(); } void func1() { func2(); } int main() { func1(); return 0; } ``` 此代码使用 `CaptureStackBackTrace` 函数获取当前调用的帧数,并打印输出。该方法适用于 Windows 平台下的信息采集和调试分析。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值