2012-03-04 61 views
11

我的問題與此SO post和一些其他alike有關。我想知道調用者函數的名稱,因爲在聲明失敗時,我不知道哪個函數將垃圾值傳遞給被調用者。一種方法是檢查所有可以調用此函數的函數,但這非常麻煩。跟蹤斷言失敗時如何知道來電函數

即使依賴於平臺,您是否可以提出更好的解決方案?我正在使用g ++ 4.6。提前致謝。

+1

你就不能在調試器中看到的堆棧跟蹤運行的程序? – sth 2012-03-04 14:56:34

+3

有很多使用情況下,你不能這樣做 – Coren 2012-03-04 15:03:30

回答

2

參見backtrace()

例如

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

void bar() { 
    void* callstack[128]; 
    int i, frames = backtrace(callstack, 128); 
    char** strs = backtrace_symbols(callstack, frames); 
    for (i = 0; i < frames; ++i) { 
    printf("%s\n", strs[i]); 
    } 
    free(strs); 
} 

int foo() { 
    bar(); 
    return 0; 
} 

int main() { 
    foo(); 
    return 0; 
} 

輸出:

0 a.out        0x0000000100000e24 bar + 28 
1 a.out        0x0000000100000e81 foo + 14 
2 a.out        0x0000000100000e96 main + 14 
3 a.out        0x0000000100000e00 start + 52 
4 ???         0x0000000000000001 0x0 + 1 

參見:

How to generate a stacktrace when my gcc C++ app crashes

4

您在glibc中有backtrace函數。它可以讓你有完整的跟蹤,調用者函數或方法。

如果只想來電,這裏還有specific functionsGCC只是這樣的:

__builtin_frame_address(int level); 

隨着level == 1你有來電的功能。有關如何使用它的更多詳細信息,請參見this post

下面是示例程序,它是在文檔中:

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

/* Obtain a backtrace and print it to stdout. */ 
void 
print_trace (void) 
{ 
    void *array[10]; 
    size_t size; 
    char **strings; 
    size_t i; 

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

    printf ("Obtained %zd stack frames.\n", size); 

    for (i = 0; i < size; i++) 
    printf ("%s\n", strings[i]); 

    free (strings); 
} 

/* A dummy function to make the backtrace more interesting. */ 
void 
dummy_function (void) 
{ 
    print_trace(); 
} 

int 
main (void) 
{ 
    dummy_function(); 
    return 0; 
} 
+0

我發現它也便於發出'backtrace'本身的結果(原始指針)。然後你可以使用'addr2line'命令行工具將它轉換爲實際的源文件名和行號。 – 2012-03-04 14:59:36

+0

非常感謝。但如何獲取函數的名稱?這似乎只打印一些地址。請原諒我的無知。 – user984260 2012-03-04 15:00:36

+0

在字符串[i]中,您有函數名稱和其他鏈接的dlinfo,它甚至可以向您顯示更多信息 – Coren 2012-03-04 15:02:35