Eorlindr
Eorlindr

Reputation: 39

How to see stack trace by pointer

I have the only pointer to some allocated memory, can I get a stack trace in the code by that pointer?

I know how to get a stack trace from a method, but what if I catch an exception in another method - can I get a stack trace?

Upvotes: 0

Views: 465

Answers (2)

Craig Estey
Craig Estey

Reputation: 33631

For best results, compile without optimization.

Under gcc [and maybe clang], you can use: __builtin_frame_address and __builtin_return_address. See man gcc for details [or just websearch for them].

You can also look at getcontext. It documents the ucontext_t struct and the mcontext_t struct.

Also, by using sigaction [with SA_SIGINFO], your signal handler can receive a pointer to a siginfo_t and a pointer to a ucontext_t.

In the past, I've been able to use combinations of the above to generate a stack trace from a signal handler (see man 7 signal for details on what functions you can safely call from a signal handler).

I was even able to coerce multiple threads to do this, usually, by sending a signal to the individual threads and each handler would dump the stack [with register values] for its given thread stack.


It helps to know what you want to achieve (e.g. debugging).

Normally, one uses an external ptrace based program (e.g. gdb or strace) to get information.

Or, you can instrument your code with debug printf calls to get a detailed list of who called what, with what values, etc.

For really tough debug issues, you may be able to write your own custom ptrace program, that your target program is aware of, and, they can work together to solve the problem.

Or, some combination of all of the above.

Upvotes: 1

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5786

In computing, a stack trace (also called stack backtrace or stack traceback) is a report of the active stack frames at a certain point in time during the execution of a program.

It will allow you to track the sequence of function calls and the list of stack frames of the functions that you called. A pointer variable has nothing to do with stack trace. It just holds an address.

Upvotes: 0

Related Questions