We use CentOS for most of our servers, and we us C for some of our programming. Here’s a quick reminder on how to enable C debugging for CentOS and using the GNU debugger.
Compiling
Before you begin, make sure you have included -g in your compiler command so that it collects the required debug info for gdb.
Enabling core dumps
First, to enable debugging you need to get a core dump! If your program doesn’t core dump, that means its probably running just fine and you don’t need to debug it. Congratulations!
However, if your program core dumps but you can’t find the file, it is because the kernel is redirecting your core dump somewhere else. Take a look inside the core pattern file to see where it is going.
cat /proc/sys/kernel/core_pattern
If you see something like this:
|/usr/libexec/abrt-hook-ccpp %s %c %p %u %g %t e
Then your core dumps are being redirected to abrt-ccpp.
The easiest way to fix that is to turn off the abrt-ccpp service:
/etc/init.d/abrt-ccpp stop
Now check the core pattern file again and it should look like this:
# cat /proc/sys/kernel/core_pattern core
Now when your program crashes, you’ll get a file called core.**** where **** is (hopefully) the process id.
Check ulimit
You also need to check the ulimit for core dumps:
ulimit -c
If this returns 0 set it to unlimited so you can save the core dump:
ulimit -c unlimited
Using gdb
Now that you have a core dump, you can use gdb to look at your code and see what is happening.
The command is
gdb <executable> <core.***>
where executable is your compiled executable code that caused the core dump and core.*** is the core dumped file.
This will open up gdb and read the code. The first command to use is bt for back trace:
(gdb) bt
This will print the back trace for the core dump. There are frames listed with numbers on the left (#1 through #n). You can choose one of those to explore more in depth information:
frame 6
Will choose the block next to #6.
Now you can use gdb commands to explore what is going on:
- list – shows the code around the point of the dump
- info locals – lists the variables and their content
- print variable – prints the value of a variable.