How to programmatically cause a core dump in C/C++

hhafez picture hhafez · Jun 11, 2009 · Viewed 81k times · Source

I would like to force a core dump at a specific location in my C++ application.

I know I can do it by doing something like:

int * crash = NULL;
*crash = 1;

But I would like to know if there is a cleaner way?

I am using Linux by the way.

Answer

paxdiablo picture paxdiablo · Jun 11, 2009

Raising of signal number 6 (SIGABRT in Linux) is one way to do it (though keep in mind that SIGABRT is not required to be 6 in all POSIX implementations so you may want to use the SIGABRT value itself if this is anything other than quick'n'dirty debug code).

#include <signal.h>
: : :
raise (SIGABRT);

Calling abort() will also cause a core dump, and you can even do this without terminating your process by calling fork() followed by abort() in the child only - see this answer for details.