1

Possible Duplicate:
How can one grab a stack trace in C?

Hi,

I would like to know how to print the contents of the current program stack (using C language).

say for eg.

    call_some_function() 
{
    ...
    ...
           print_stack_till_now();
    return something;
    }

    call_some_other_function() 
{
    ...
    ...
           print_stack_till_now();
    return something;
    }

    main()
    {
       print_stack_till_now();
       call_some_function();
       print_stack_till_now();
       call_some_other_function();
       print_stack_till_now();

       return 0;
    }

In the prev example (may be not an example exactly :)) when I call the print_stack_till_now() function I should be able to print the current stack built till that point (including the newer function call entries, return location, their arguments etc.)

Is such a function possible in C language (even inlined assembly). Please point me to the theory (or existing code would be even better) needed to write such a function.

In gdb we can use backtrace to look at the current stack, I'm looking for something similar. Why do I need this ?... just wanted to learn.

Thank you.

Community
  • 1
  • 1
jailed
  • 105
  • 3
  • 8
  • i dont think theres any native C function, so itll take more information such as the OS and stuff for anyone to give you a working answer. For what its worth tho, each of those calls in your example is likely to return/output the exact same thing. – jon_darkstar Mar 27 '11 at 22:47
  • 2
    http://stackoverflow.com/questions/105659/how-can-one-grab-a-stack-trace-in-c – jon_darkstar Mar 27 '11 at 22:48
  • @jon_darkstar: I edited the code. I think this is what I meant but wrote a different snippet. Thanks @Ubiquite: Linux – jailed Mar 27 '11 at 22:56
  • http://wiki.linuxquestions.org/wiki/Core_dump – BenjaminB Mar 27 '11 at 23:04

1 Answers1

1

There's no portable way to do this for the simple reason that C by itself doesn't define the concept of a stack data structure. It's completely open to the implementation how it does automatic storage and returns from function calls.

That being said most implementations provide some kind of stack unwinding mechanism. For example GCC/glibc provides the runtime specific function backtrace

http://www.gnu.org/s/libc/manual/html_node/Backtraces.html

There are similar stack unwinders for other plattforms. And of course you can implement your own backtracing mechanisms through a global, thread local storage array (it can be static and must provide only enough entries for how many function calls are supported by the stack size), where at each function call the calling module (using C preprocessor __FILE__), the line (C preprocessor __LINE__) and the called function (some additional preprocessor magic) are placed.

datenwolf
  • 159,371
  • 13
  • 185
  • 298