Debugging a segfault in a python ctypes project

Danny PriceDanny Price
1 min read

When a pure Python program crashes, a verbose traceback is printed. The traceback makes it easy to find where in your code things went wrong. However, if your Python program is wrapping some C code, you need to run through a few hoops to see what went wrong.

To debug, we first need to capture a 'core dump', which is the memory contents at the time of the crash. We can use the ulimit command to do so:

ulimit -c unlimited

We also need to make sure the shared object was compiled with the -g gcc flag, which generates debug information used by the gdb debugger.

After running ulimit, go ahead and run your program again. You should see (core dumped) appended to the output of the segfault error message.

After you have generated the core dump, you can run gdb with

gdb /opt/conda/bin/python core.1700

(where core.1700 is the name of the core file that was produced).

From here you can use gdb as with regular C code -- a good starting point is to look at the backtrace by typing bt. To exit, type quit.

0
Subscribe to my newsletter

Read articles from Danny Price directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Danny Price
Danny Price