What Causes a Python Segmentation Fault

Embedding Python to C++ Receiving Error Segmentation fault (core dumped)

After each and every one of those statements, you will need to check for errors, using something of the form:

if (varname == NULL) {
cout << “An error occured” << endl;
PyErr_Print();
return EXIT_FAILURE;
}

This will check if the python layer through an error; and if so will ask it to print the Python traceback to the screen, and exit. You can use this traceback to figure out what your error is.

Any of those functions can fail, and you need to check for failure before you continue. Using the Python C API is extremely fiddly because of this. Most C API functions that return a pointer return NULL on error, and passing NULL into any function without checking it first is bound to result in a crash.

You get a segmentation fault from accessing a NULL pointer, as nearly all modern systems map access of NULL to a segmentation fault or crash of some sort to catch programming errors.

Segmentation Fault Error while doing big calculations in python

Make it non-recursive, too deep recursion overflows stack and stack is usually just few megabytes. After stack overflow your program crashes with segmentation fault.

Your code modified to become non-recursive (which doesn't crash):

Try it online!

def collatz(n):
while True:
if (n == -1 or n == 1 or n == -17 or n == -17 -2**4096):
print('break found', n)
return
if str(n)[-1] in ['1','3','5','7','9']:
#print(n)
n = 3 * n + 1
else:
n = n // 2


collatz(2**4000 + 1)

Output:

break found 1

BTW, classical Collatz problem can be solved with much shorter and faster code, for example like this:

Try it online!

def collatz(n):
for i in range(1 << 50):
if n == 1:
return i
n = 3 * n + 1 if n & 1 else n >> 1

print('Collatz chain length:', collatz(2**4000 + 1))

Output:

Collatz chain length: 29400

Also just for a side note I want to mention Python library GMPY2 based on famous C-based GMP. It has very optimized long integer arithmetics code and can be used to boost your code if you realy need speed.

On Windows gmpy2 can be installed by downloading it from here and installing through pip install gmpy2‑2.0.8‑cp39‑cp39‑win_amd64.whl. On Linux it can be installed through sudo apt install python3-gmpy2.

After installation you can use gmpy2 in a very simple manner, like in function collatz_gmpy() below:

Try it online!

def collatz_py(n):
for i in range(1 << 50):
if n == 1:
return i
n = 3 * n + 1 if n & 1 else n >> 1

def collatz_gmpy(n):
from gmpy2 import mpz
n = mpz(n)
for i in range(1 << 50):
if n == 1:
return i
n = 3 * n + 1 if n & 1 else n >> 1

def test():
import timeit
n = 2 ** 100000 + 1
for i, f in enumerate([collatz_py, collatz_gmpy]):
print(f.__name__, round(timeit.timeit(lambda: f(n), number = 1), 3), 'secs')

test()

Output:

collatz_py 7.477 secs
collatz_gmpy 2.916 secs

As one can see GMPY2 variant gives 2.56x times speedup compared to regular Python's variant.



Related Topics



Leave a reply



Submit