Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 710
hhafez Avatar asked Jun 11 '09 03:06

hhafez


People also ask

What causes a core dump in C?

Core Dump (Segmentation fault) in C/C++ It happens due to reasons like when code tries to write on read only memory or tries to access corrupt memory location.

What generates a core dump?

Core dumps are generated when the process receives certain signals, such as SIGSEGV, which the kernels sends it when it accesses memory outside its address space. Typically that happens because of errors in how pointers are used. That means there's a bug in the program. The core dump is useful for finding the bug.

How do I create a core dump without killing the process?

You can use “gdb” (The GNU debugger) to dump a core of the process without killing the process and almost with no disruption of the service.


2 Answers

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.

like image 55
paxdiablo Avatar answered Sep 29 '22 06:09

paxdiablo


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 :)

like image 24
ephemient Avatar answered Sep 29 '22 05:09

ephemient