1. 程式人生 > >Linux下獲取呼叫堆疊地址

Linux下獲取呼叫堆疊地址

#include <stdio.h>
#include <stdlib.h>
#include <execinfo.h>

void get_stack_info(char *buf, int len)
{
#define MAX_BACK_TRACE_DEPTH 100
#define MAX_STACK_SIZE       64
    if (buf == NULL || len <= 0)
    {
        return;
    }

    void *array[MAX_BACK_TRACE_DEPTH];
    size_t size;
    char **strings;
    char *p = buf;
    size_t i;
    int n;

    size = backtrace(array, MAX_BACK_TRACE_DEPTH);
    strings = backtrace_symbols(array, size);

    n = snprintf(p, len, "********************************************\r\n");
    p += n;
    len -= n;

    n = snprintf(p, len, "Call stack:\r\n");
    p += n;
    len = len - n;

    for (i = 0; i < size; ++i)
    {
        if (len < 0)
        {
            break;
        }

        char *pl = strstr(strings[i], "[");
        char *pr = strstr(strings[i], "]");
        char addr[MAX_STACK_SIZE];
        memset(addr, '\0', sizeof(addr));
        strncpy(addr, pl + 1, pr - pl - 1);
        n = snprintf(p , len , "  ip[%02d]    : %s\r\n", (int)i, addr);
        p += n;
        len -= n;
    }

    n = snprintf(p, len, "*******************************************\r\n");
    p += n;
    len -= n;

    free(strings);
}


int demo()
{
	char buf[2048];
	memset(buf, 0, sizeof(buf));
	get_stack_info(buf, sizeof(buf) - 1);
	printf("%s\r\n", buf);
}              


int main(int argc, char **argv)
{
	demo();
	
	return 0;
}