issue with backtrace() off by 1

39 Views Asked by At

I'm attempting to get a stacktrace using backtrace and backtrace_symbols. This is giving me a stacktrace, but the issue is its giving me an incorrect stacktrace in main()

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

void old_backtrace()
{
    int m_maxNumFrames = 30;
    void** m_frames = (void**)malloc(m_maxNumFrames * sizeof(void*));
    int m_numFrames = backtrace(m_frames, m_maxNumFrames);

    char** strs = backtrace_symbols(m_frames, m_numFrames);

    printf("Call stack:\n");
    for (int i = 0; i < m_numFrames; ++i) {
        printf("%s\n", strs[i]);
    }
}

int main(int argn, char** argc) {

    old_backtrace();

    char* foo;

}

I'm compiling it with gcc -g3 -rdynamic -O0 test.cpp -o output on gcc13.1

when I run it, I get

./output(_Z13old_backtracev+0x39) [0x555fc6b201e2]
./output(main+0x18) [0x555fc6b20259]
/lib/x86_64-linux-gnu/libc.so.6(+0x29d90) [0x7f27645f9d90]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x80) [0x7f27645f9e40]
./output(_start+0x25) [0x555fc6b200e5]

so far so good. If I look at the first address

/home/dev/permanent_data/stack/test.cpp:9 (discriminator 1)

which is exactly where I'm calling backtrace. If I look at the address in main, however

addr2line -e output main+0x18 /home/dev/permanent_data/stack/test.cpp:25

Its giving me line 25, which is the last line of main(), not where old_backtrace is called. I'm seeing this in more complicated examples also. However, if I subtract 1 (0x17) it gives me the correct line. While I could do this, I would like to understand why.

0

There are 0 best solutions below