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

CGdb

C Problem Overview


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 ?? ()

C Solutions


Solution 1 - C

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.

Solution 2 - C

Run your program under GDB. When the segfault occurs, GDB will inform you of the line and statement of your program, along with the variable and its associated address.

You can use the "print" (p) command in GDB to inspect variables. If the crash occurred in a library call, you can use the "frame" series of commands to see the stack frame in question.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnornagonView Question on Stackoverflow
Solution 1 - CcafView Answer on Stackoverflow
Solution 2 - CYann RaminView Answer on Stackoverflow