Printing gdb output using C/C++ function

Oct 11, 2009 at 11:13am
Hi Guys,

Is there a way that we can print gdb output on segmentation fault from C program?
I mean, we just have to catch SIGSEGV and call the function with it right?
That way, if segfault occurs then I won't have to debug my code, it'll directly print the gdb output for me.

Thanks in advance
Oct 11, 2009 at 11:32am
If you are using an IDE it would tell you the line automatically -depending on which IDE you have-
Oct 11, 2009 at 11:41am
Thanks for the reply Bazzy.
Actually, what I want is that I should get the exact output of the gdb at segmentation fault instead of "Command terminated" or "Segmentation fault" as output on the terminal.

I was reading about the backtrace function. man 3 backtrace . Wrote a code to check out the output of backtrace but it's not similar to what gdb shows. Of-course it might be similar to the output of bt on gdb.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<execinfo.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/signal.h>

void    handler(int sig) { 
    void* callstack[128];
    size_t size ; 
    size = backtrace(callstack, 10) ; 
    fprintf(stderr, "error: signal %d \n",sig);
    backtrace_symbols_fd(callstack, size, 2); 
    exit(1);
}

void foo() { 
    int *foo = (int *) -1; 
    printf("%d\n",*foo);
}

int main() { 
    signal(SIGSEGV,handler);  
    foo();
    return 0;
}

Ref: http://stackoverflow.com/questions/76822/how-to-generate-a-stacktrace-when-my-c-app-crashes-using-gcc-compiler

I want to see output like

Reading symbols for shared libraries ++. done

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0xffffffff
0x00001dc9 in foo () at segcatch.cc:17
17	    printf("%d\n",*foo);



Thanks
Oct 11, 2009 at 2:53pm
Read up on sigaction() if your platform has it. You can get at least the address of the fault
and the EIP (instruction pointer) of the fault. It would be significantly non-trivial to try
to map the EIP back to a line number. You are better off using the addr2line utility (if
using GCC). Give addr2line an executable and an EIP and it will print out the source
file and line number of the EIP.

Oct 11, 2009 at 8:18pm
Thanks for the reply Jsmith.
I will look into this.
Last edited on Oct 11, 2009 at 8:18pm
Topic archived. No new replies allowed.