Code # 1: A C extension function that shows how to use elements in an iterable.
The code above reflects similar code in Python.
PyObject_GetIter() is the same as calling
iter() to get an iterator. The
PyIter_Next() function calls the next method on the iterator, returning the next element, or NULL if there are no more elements. Make sure you are careful with memory management —
Py_DECREF() must be called on both the generated elements and the iterator object itself to avoid memory leaks.
Diagnosing segmentation faults —
The interpreter crashes severely due to a segmentation fault, bus error, access violation, or other fatal error. Likes getting a Python trace that shows where the program was running at the time of the crash.
The error handler module can help you solve this problem. Include the following code in your program.
Code # 2:
Or start Python with the -Xfaulthandler parameter, like this:
bash% python3 -Xfaulthandler program.py
Last but not least, the PYTHONFAULTHANDLER environment variable can be set appropriately. If an error handler is enabled, fatal errors in C extensions will cause Python traces to be printed on failures. For example:
Fatal Python error: Segmentation fault Current thread 0x00007fff71106cc0: File "example.py", line 6 in foo File "example.py", line 10 in bar File "example.py", line 14 in spam File "example.py", line 19 in Segmentation fault
While this doesn’t tell you where things went wrong in the C code, at least it can tell you how it happened with Python.
Error handler will show a trace of the Python code stack running at the time of the crash. At least this will show the top level extension function that was called. You can use pdb or another Python debugger to examine the Python code flow leading to the error.