Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get GDB to tell me what address caused a segfault?

Tags:

c

gdb

I'd like to know if my program is accessing NULL pointers or stale memory.

The backtrace looks like this:

 Program received signal SIGSEGV, Segmentation fault. [Switching to Thread 0x2b0fa4c8 (LWP 1333)] 0x299a6ad4 in pthread_mutex_lock () from /lib/libpthread.so.0 (gdb) bt #0  0x299a6ad4 in pthread_mutex_lock () from /lib/libpthread.so.0 #1  0x0058e900 in ?? () 
like image 215
nornagon Avatar asked Jun 09 '10 05:06

nornagon


People also ask

How do you know where a segfault occurs?

Use debuggers to diagnose segfaultsStart your debugger with the command gdb core , and then use the backtrace command to see where the program was when it crashed. This simple trick will allow you to focus on that part of the code.

Can you recover from a segfault?

On both Windows and Linux, the segfault handler function is passed a "context struct", which includes the state of the registers at the failure site. Ostensibly, this is so people can repair the problem that caused the segfault (it also lets you do nifty things like userspace segment handling).


1 Answers

With GDB 7 and higher, you can examine the $_siginfo structure that is filled out when the signal occurs, and determine the faulting address:

(gdb) p $_siginfo._sifields._sigfault.si_addr 

If it shows (void *) 0x0 (or a small number) then you have a NULL pointer dereference.

like image 200
caf Avatar answered Oct 06 '22 11:10

caf