Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get stacktrace during an application crash - c/c++

I am a java developer trying my hands on C-C++ code. Basically I have some build script that uses Visual Studio components to build the application libraries - dlls. We do not use Visual Studio IDE to debug.

But whenever we face some crash in our application, we have to enter the debug statements line by line and need to check the exact line of code in which it is crashing.

Is there any API in C/C++ which would write the stack trace into a file during the crash of our program?

Some kind of event listener that would be called during a program exit and that could print the stack trace and error information into a log file.

I have seen many questions related to this but I am not able to get how to handle this in code rather than debugging tools. I feel Java is very much advanced with respect to error handling.

Thanks in advance!

like image 305
Mohamed Iqzas Avatar asked Mar 13 '23 06:03

Mohamed Iqzas


1 Answers

The Standard does not give you any facilites for this. That said, you can use OS-specific APIs to get what you want. On windows, the easiest is probably to use StackWalker. You do need to take care of SEH oddities yourself. I suggest this article for more information.

On POSIX platforms, you can use the backtrace function from glibc.

In general, both require your program to be compiled with debug information. It is also possible to create crash dumps without symbol names (see Minidumps on Windows), but you will need to decode them (which Visual Studio does for you for example, but you mentioned in your post that you don't use it).

Also, keep in mind that writing crash dumps from a crashing process is very error-prone (since you really have no idea what state your application is at that time). You might get more reliable results if you write the crash dumps from another process. Earlier I've put together a simple example out-of-process crash handler that demonstrates how to implement that.

like image 90
Tamás Szelei Avatar answered Mar 20 '23 07:03

Tamás Szelei