Segmentation Fault

Segmentation fault is an error caused by accessing invalid memory, e.g., accessing variable that has already been freed, writing to a read-only portion of memory, or accessing elements out of range of the array, etc. However, sometimes, the segfault will not show up instantly; instead, the memory leak gradually accumulates, and finally cause impossible to access variable or require extra memory (e.g., vector.resize()).

GDB and Valgrind are great helpful tools to detect and correct segmentation fault and memory leaks.

1. GDB

gdb can be used to figure out why the program causes a segmentation fault, i.e., accessing an invalid memory address.

A backtrace is a summary of how your program got where it is. It shows one line per frame, for many frames, starting with the currently executing fram (#0), followed by its caller (#1), and on up to the stack.

 
$gdb ./myprog
#-- run to receive the SIGSEGV signal from OS
$(gdb) run <arg1> <arg2>
#-- print a backtrace of the entire stack: one line per frame for all frames in the stack (^c)
$(gdb) backtrace/bt
#-- print only the innermost n frames
$(gdb) bt n
#-- print only the outermost n frames
$(gdb) bt -n
#-- switch to a stack frame
$(gdb) frame 3
#-- display info about the current stack frame
$(gdb) info frame
#-- display the list of local variables and values
$(gdb) info locals
#-- display the list of arguments
$(gdb) info args
#-- set a break point when meet certain value
$(gdb) break src/myprog.c:10 if val=100
#-- use watchpoint
$(gdb) watch val #-- condition <breakpoint num> i == 5

2. Valgrind

The Valgrind tool suite provides a number of debugging and profiling tools, among which Memcheck is the most popular one to detect memory-related errors leading to crashes and unpredictable behavior.

running program under Memcheck

Memcheck can only really detect two kinds of errors, use of illegal addresses, and use of undefined values, which are generally enough to discover all sorts of memory-management nasties in the code.

 
xxxxxxxxxx
$valgrind --leak-check=yes myprog arg1 arg2
$valgrind --tool=memcheck --leak-check=yes --show-reachable=yes --num-callers=20 --track-fds=yes myprog
#-- redirect error messages to file
$>& val.log 2) 
#-- or
$valgrind --log-file="filename"

[1]. [The Valgrind quick start guide][http://valgrind.org/docs/manual/quick-start.html]

[2]. [Using and understanding the Valgrind core][http://valgrind.org/docs/manual/manual-core.html]

[3]. [An overview of Valgrind][http://valgrind.org/docs/manual/manual-intro.html#manual-intro.overview]