Skip to content

Instantly share code, notes, and snippets.

@xaxxon
Created July 29, 2016 06:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xaxxon/2845c7376b21e5699872a00292f48340 to your computer and use it in GitHub Desktop.
Save xaxxon/2845c7376b21e5699872a00292f48340 to your computer and use it in GitHub Desktop.
class StackTraceException : public std::exception {
protected:
static constexpr int STACK_POINTER_COUNT = 100;
void * stack_pointers[STACK_POINTER_COUNT];
std::size_t stack_pointers_filled = 0;
mutable std::string stacktrace;
public:
StackTraceException();
~StackTraceException();
virtual const char *what() const noexcept override;
};
constexpr int StackTraceException::STACK_POINTER_COUNT;
StackTraceException::StackTraceException() {
stack_pointers_filled = backtrace(stack_pointers, STACK_POINTER_COUNT);
}
StackTraceException::~StackTraceException() { }
const char* StackTraceException::what() const noexcept {
// this is quite expensive, so only do it on demand
if (stacktrace == "") {
char **symbols = nullptr;
symbols = backtrace_symbols(stack_pointers, stack_pointers_filled);
std::stringstream stream;
for (int i = 0; i < stack_pointers_filled; i++) {
stream << symbols[i] << std::endl;
}
stacktrace = stream.str();
free(symbols);
}
return stacktrace.c_str();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment