views:

3055

answers:

7

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.

+13  A: 

As listed in the signal manpage, any signal with the action listed as 'core' will force a core dump. Some examples are:

SIGQUIT       3       Core    Quit from keyboard
SIGILL        4       Core    Illegal Instruction
SIGABRT       6       Core    Abort signal from abort(3)
SIGFPE        8       Core    Floating point exception
SIGSEGV      11       Core    Invalid memory reference

Make sure that you enable core dumps:

ulimit -c unlimited
Suvesh Pratapa
+16  A: 
#include <stdlib.h>   // C
//#include <cstdlib>  // C++

void core_dump(void)
{
    abort();
}
Jonathan Leffler
+2  A: 

You can use kill(2) to send signal.

#include <sys/types.h>
#include <signal.h>
int kill(pid_t pid, int sig);

So,

kill(getpid(), SIGSEGV);
eed3si9n
So kill(getpid(), SIGxxx);?
Jonathan Leffler
Yup. Added that to the answer.
eed3si9n
SIGKILL doesn't dump core...
Jonathan Leffler
@Jonathan Leffler, you are right. Changed to SIGSEGV.
eed3si9n
+4  A: 

abort();

Related, sometimes you'd like a back trace without an actual core dump, and allow the program to continue running: check out glibc backtrace() and backtrace_symbols() functions: http://www.gnu.org/s/libc/manual/html_node/Backtraces.html

smcameron
+9  A: 

Raising of signal number 6 (SIGABRT) is one way to do it.

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

Calling abort() will also do it.

paxdiablo
SIGABRT is not required to be signal number 6 (though it often is - and is, specifically, on Linux).
Jonathan Leffler
No, you're right, it's not but I tend not to worry too much about the correctness of debug code. If that escapes into the wild, the cleanliness of my code is the least of my worries :-)
paxdiablo
+15  A: 

A few years ago, Google released the coredumper library.

Overview

The coredumper library can be compiled into applications to create core dumps of the running program -- without terminating. It supports both single- and multi-threaded core dumps, even if the kernel does not natively support multi-threaded core files.

Coredumper is distributed under the terms of the BSD License.

Example

This is by no means a complete example; it simply gives you a feel for what the coredumper API looks like.

#include <google/coredumper.h>
...
WriteCoreDump('core.myprogram');
/* Keep going, we generated a core file,
 * but we didn't crash.
 */

It's not what you were asking for, but maybe it's even better :)

ephemient
+1  A: 
#include <assert.h>
.
.
.
     assert(!"this should not happen");
sigjuice