Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python tracing a segmentation fault

People also ask

How do you trace a segmentation fault in Python?

Alternatively, one can start a script like this: gdb --args python3 script.py and then execute the run command from the gdb-shell. After the script crashed, one can execute the backtrace command to get the trace.

How do you trace a segmentation fault?

Use a debugger, such as gdb or if this is not applicable a strace tool to get a better insight into where the segfault occurs. If you use gcc , make sure you compile with -g switch to include debugging information. Then, gdb will show you the exact location in a source code where it segfaults.


If you are on linux, run python under gdb

gdb python
(gdb) run /path/to/script.py
## wait for segfault ##
(gdb) backtrace
## stack trace of the c code

Here's a way to output the filename and line number of every line of Python your code runs:

import sys

def trace(frame, event, arg):
    print("%s, %s:%d" % (event, frame.f_code.co_filename, frame.f_lineno))
    return trace

def test():
    print("Line 8")
    print("Line 9")

sys.settrace(trace)
test()

Output:

call, test.py:7
line, test.py:8
Line 8
line, test.py:9
Line 9
return, test.py:9

(You'd probably want to write the trace output to a file, of course.)


Segfaults from C extensions are very frequently a result of not incrementing a reference count when you create a new reference to an object. That makes them very hard to track down as the segfault occurs only after the last reference is removed from the object, and even then often only when some other object is being allocated.

You don't say how much C extension code you have written so far, but if you're just starting out consider whether you can use either ctypes or Cython. Ctypes may not be flexible enough for your needs, but you should be able to link to just about any C library with Cython and have all the reference counts maintained for you automatically.

That isn't always sufficient: if your Python objects and any underlying C objects have different lifetimes you can still get problems, but it does simplify things considerably.


I came here looking for a solution to the same problem, and none of the other answers helped me. What did help was faulthandler, and you can install it in Python 2.7 just using pip install.

faulthandler was introduced to Python only in version 3.3, that was released in September 2012, which was after most other answers here were written.