Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>For Linux and I believe Mac OS X, if you're using gcc, or any compiler that uses glibc, you can use the backtrace() functions in <code>execinfo.h</code> to print a stacktrace and exit gracefully when you get a segmentation fault. Documentation can be found <a href="http://www.gnu.org/software/libc/manual/html_node/Backtraces.html" rel="noreferrer">in the libc manual</a>.</p> <p>Here's an example program that installs a <code>SIGSEGV</code> handler and prints a stacktrace to <code>stderr</code> when it segfaults. The <code>baz()</code> function here causes the segfault that triggers the handler:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;execinfo.h&gt; #include &lt;signal.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; void handler(int sig) { void *array[10]; size_t size; // get void*'s for all entries on the stack size = backtrace(array, 10); // print out all the frames to stderr fprintf(stderr, "Error: signal %d:\n", sig); backtrace_symbols_fd(array, size, STDERR_FILENO); exit(1); } void baz() { int *foo = (int*)-1; // make a bad pointer printf("%d\n", *foo); // causes segfault } void bar() { baz(); } void foo() { bar(); } int main(int argc, char **argv) { signal(SIGSEGV, handler); // install our handler foo(); // this will call foo, bar, and baz. baz segfaults. } </code></pre> <p>Compiling with <code>-g -rdynamic</code> gets you symbol info in your output, which glibc can use to make a nice stacktrace:</p> <pre><code>$ gcc -g -rdynamic ./test.c -o test </code></pre> <p>Executing this gets you this output:</p> <pre><code>$ ./test Error: signal 11: ./test(handler+0x19)[0x400911] /lib64/tls/libc.so.6[0x3a9b92e380] ./test(baz+0x14)[0x400962] ./test(bar+0xe)[0x400983] ./test(foo+0xe)[0x400993] ./test(main+0x28)[0x4009bd] /lib64/tls/libc.so.6(__libc_start_main+0xdb)[0x3a9b91c4bb] ./test[0x40086a] </code></pre> <p>This shows the load module, offset, and function that each frame in the stack came from. Here you can see the signal handler on top of the stack, and the libc functions before <code>main</code> in addition to <code>main</code>, <code>foo</code>, <code>bar</code>, and <code>baz</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload