code_junkie

How can one grab a stack trace in C?

Nov 11th, 2011
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. unw_cursor_t cursor; unw_context_t uc;
  2. unw_word_t ip, sp;
  3. unw_getcontext(&uc);
  4. unw_init_local(&cursor, &uc);
  5. unsigned long a[100];
  6. int ctr = 0;
  7.  
  8. while (unw_step(&cursor) > 0) {
  9. unw_get_reg(&cursor, UNW_REG_IP, &ip);
  10. unw_get_reg(&cursor, UNW_REG_SP, &sp);
  11. if (ctr >= 10) break;
  12. a[ctr++] = ip;
  13. }
  14.  
  15. #include <execinfo.h>
  16. #include <stdio.h>
  17. ...
  18. void* callstack[128];
  19. int i, frames = backtrace(callstack, 128);
  20. char** strs = backtrace_symbols(callstack, frames);
  21. for (i = 0; i < frames; ++i) {
  22. printf("%sn", strs[i]);
  23. }
  24. free(strs);
  25. ...
  26.  
  27. class MyException : public std::exception {
  28.  
  29. char ** strs;
  30. MyException( const std::string & message ) {
  31. int i, frames = backtrace(callstack, 128);
  32. strs = backtrace_symbols(callstack, frames);
  33. }
  34.  
  35. void printStackTrace() {
  36. for (i = 0; i
  37.  
  38.  
  39. ...
  40.  
  41.  
  42.  
  43. try {
  44. throw MyException("Oops!");
  45. } catch ( MyException e ) {
  46. e.printStackTrace();
  47. }
  48.  
  49. -rdynamic
Add Comment
Please, Sign In to add comment