Ошибка сегментирования стек памяти сброшен на диск python

I am implementing Kosaraju’s Strong Connected Component(SCC) graph search algorithm in Python.

The program runs great on small data set, but when I run it on a super-large graph (more than 800,000 nodes), it says «Segmentation Fault».

What might be the cause of it? Thank you!


Additional Info:
First I got this Error when running on the super-large data set:

"RuntimeError: maximum recursion depth exceeded in cmp"

Then I reset the recursion limit using

sys.setrecursionlimit(50000)

but got a ‘Segmentation fault’

Believe me it’s not a infinite loop, it runs correct on relatively smaller data. It is possible the program exhausted the resources?

Community's user avatar

asked Apr 5, 2012 at 20:28

xiaolong's user avatar

6

This happens when a python extension (written in C) tries to access a memory beyond reach.

You can trace it in following ways.

  • Add sys.settrace at the very first line of the code.
  • Use gdb as described by Mark in this answer.. At the command prompt

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

Community's user avatar

answered Apr 5, 2012 at 20:32

Shiplu Mokaddim's user avatar

Shiplu MokaddimShiplu Mokaddim

56.2k17 gold badges139 silver badges185 bronze badges

7

I understand you’ve solved your issue, but for others reading this thread, here is the answer: you have to increase the stack that your operating system allocates for the python process.

The way to do it, is operating system dependant. In linux, you can check with the command ulimit -s your current value and you can increase it with ulimit -s <new_value>

Try doubling the previous value and continue doubling if it does not work, until you find one that does or run out of memory.

answered Jul 6, 2012 at 19:19

Davide's user avatar

DavideDavide

16.9k11 gold badges52 silver badges68 bronze badges

5

Segmentation fault is a generic one, there are many possible reasons for this:

  • Low memory
  • Faulty Ram memory
  • Fetching a huge data set from the db using a query (if the size of fetched data is more than swap mem)
  • wrong query / buggy code
  • having long loop (multiple recursion)

Paul's user avatar

Paul

5,3831 gold badge30 silver badges37 bronze badges

answered Nov 4, 2013 at 21:04

Sadheesh's user avatar

SadheeshSadheesh

8859 silver badges6 bronze badges

Updating the ulimit worked for my Kosaraju’s SCC implementation by fixing the segfault on both Python (Python segfault.. who knew!) and C++ implementations.

For my MAC, I found out the possible maximum via :

$ ulimit -s -H
65532

answered Nov 18, 2016 at 4:08

Rock's user avatar

RockRock

1773 silver badges11 bronze badges

2

Google search found me this article, and I did not see the following «personal solution» discussed.


My recent annoyance with Python 3.7 on Windows Subsystem for Linux is that: on two machines with the same Pandas library, one gives me segmentation fault and the other reports warning. It was not clear which one was newer, but «re-installing» pandas solves the problem.

Command that I ran on the buggy machine.

conda install pandas

More details: I was running identical scripts (synced through Git), and both are Windows 10 machine with WSL + Anaconda. Here go the screenshots to make the case. Also, on the machine where command-line python will complain about Segmentation fault (core dumped), Jupyter lab simply restarts the kernel every single time. Worse still, no warning was given at all.

enter image description here


Updates a few months later: I quit hosting Jupyter servers on Windows machine. I now use WSL on Windows to fetch remote ports opened on a Linux server and run all my jobs on the remote Linux machine. I have never experienced any execution error for a good number of months :)

answered Feb 10, 2019 at 18:19

llinfeng's user avatar

llinfengllinfeng

1,3061 gold badge14 silver badges37 bronze badges

I was experiencing this segmentation fault after upgrading dlib on RPI.
I tracebacked the stack as suggested by Shiplu Mokaddim above and it settled on an OpenBLAS library.

Since OpenBLAS is also multi-threaded, using it in a muilt-threaded application will exponentially multiply threads until segmentation fault. For multi-threaded applications, set OpenBlas to single thread mode.

In python virtual environment, tell OpenBLAS to only use a single thread by editing:

    $ workon <myenv>
    $ nano .virtualenv/<myenv>/bin/postactivate

and add:

    export OPENBLAS_NUM_THREADS=1 
    export OPENBLAS_MAIN_FREE=1

After reboot I was able to run all my image recognition apps on rpi3b which were previously crashing it.

reference:
https://github.com/ageitgey/face_recognition/issues/294

answered Mar 22, 2019 at 12:42

Digitalf8's user avatar

Looks like you are out of stack memory. You may want to increase it as Davide stated. To do it in python code, you would need to run your «main()» using threading:

def main():
    pass # write your code here

sys.setrecursionlimit(2097152)    # adjust numbers
threading.stack_size(134217728)   # for your needs

main_thread = threading.Thread(target=main)
main_thread.start()
main_thread.join()

Source: c1729’s post on codeforces. Runing it with PyPy is a bit trickier.

answered Apr 12, 2020 at 21:02

Rustam A.'s user avatar

Rustam A.Rustam A.

8098 silver badges15 bronze badges

I’d run into the same error. I learnt from another SO answer that you need to set the recursion limit through sys and resource modules.

answered Nov 12, 2021 at 2:30

Aravind's user avatar

1

I am implementing Kosaraju’s Strong Connected Component(SCC) graph search algorithm in Python.

The program runs great on small data set, but when I run it on a super-large graph (more than 800,000 nodes), it says «Segmentation Fault».

What might be the cause of it? Thank you!


Additional Info:
First I got this Error when running on the super-large data set:

"RuntimeError: maximum recursion depth exceeded in cmp"

Then I reset the recursion limit using

sys.setrecursionlimit(50000)

but got a ‘Segmentation fault’

Believe me it’s not a infinite loop, it runs correct on relatively smaller data. It is possible the program exhausted the resources?

Community's user avatar

asked Apr 5, 2012 at 20:28

xiaolong's user avatar

6

This happens when a python extension (written in C) tries to access a memory beyond reach.

You can trace it in following ways.

  • Add sys.settrace at the very first line of the code.
  • Use gdb as described by Mark in this answer.. At the command prompt

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

Community's user avatar

answered Apr 5, 2012 at 20:32

Shiplu Mokaddim's user avatar

Shiplu MokaddimShiplu Mokaddim

56.2k17 gold badges139 silver badges185 bronze badges

7

I understand you’ve solved your issue, but for others reading this thread, here is the answer: you have to increase the stack that your operating system allocates for the python process.

The way to do it, is operating system dependant. In linux, you can check with the command ulimit -s your current value and you can increase it with ulimit -s <new_value>

Try doubling the previous value and continue doubling if it does not work, until you find one that does or run out of memory.

answered Jul 6, 2012 at 19:19

Davide's user avatar

DavideDavide

16.9k11 gold badges52 silver badges68 bronze badges

5

Segmentation fault is a generic one, there are many possible reasons for this:

  • Low memory
  • Faulty Ram memory
  • Fetching a huge data set from the db using a query (if the size of fetched data is more than swap mem)
  • wrong query / buggy code
  • having long loop (multiple recursion)

Paul's user avatar

Paul

5,3831 gold badge30 silver badges37 bronze badges

answered Nov 4, 2013 at 21:04

Sadheesh's user avatar

SadheeshSadheesh

8859 silver badges6 bronze badges

Updating the ulimit worked for my Kosaraju’s SCC implementation by fixing the segfault on both Python (Python segfault.. who knew!) and C++ implementations.

For my MAC, I found out the possible maximum via :

$ ulimit -s -H
65532

answered Nov 18, 2016 at 4:08

Rock's user avatar

RockRock

1773 silver badges11 bronze badges

2

Google search found me this article, and I did not see the following «personal solution» discussed.


My recent annoyance with Python 3.7 on Windows Subsystem for Linux is that: on two machines with the same Pandas library, one gives me segmentation fault and the other reports warning. It was not clear which one was newer, but «re-installing» pandas solves the problem.

Command that I ran on the buggy machine.

conda install pandas

More details: I was running identical scripts (synced through Git), and both are Windows 10 machine with WSL + Anaconda. Here go the screenshots to make the case. Also, on the machine where command-line python will complain about Segmentation fault (core dumped), Jupyter lab simply restarts the kernel every single time. Worse still, no warning was given at all.

enter image description here


Updates a few months later: I quit hosting Jupyter servers on Windows machine. I now use WSL on Windows to fetch remote ports opened on a Linux server and run all my jobs on the remote Linux machine. I have never experienced any execution error for a good number of months :)

answered Feb 10, 2019 at 18:19

llinfeng's user avatar

llinfengllinfeng

1,3061 gold badge14 silver badges37 bronze badges

I was experiencing this segmentation fault after upgrading dlib on RPI.
I tracebacked the stack as suggested by Shiplu Mokaddim above and it settled on an OpenBLAS library.

Since OpenBLAS is also multi-threaded, using it in a muilt-threaded application will exponentially multiply threads until segmentation fault. For multi-threaded applications, set OpenBlas to single thread mode.

In python virtual environment, tell OpenBLAS to only use a single thread by editing:

    $ workon <myenv>
    $ nano .virtualenv/<myenv>/bin/postactivate

and add:

    export OPENBLAS_NUM_THREADS=1 
    export OPENBLAS_MAIN_FREE=1

After reboot I was able to run all my image recognition apps on rpi3b which were previously crashing it.

reference:
https://github.com/ageitgey/face_recognition/issues/294

answered Mar 22, 2019 at 12:42

Digitalf8's user avatar

Looks like you are out of stack memory. You may want to increase it as Davide stated. To do it in python code, you would need to run your «main()» using threading:

def main():
    pass # write your code here

sys.setrecursionlimit(2097152)    # adjust numbers
threading.stack_size(134217728)   # for your needs

main_thread = threading.Thread(target=main)
main_thread.start()
main_thread.join()

Source: c1729’s post on codeforces. Runing it with PyPy is a bit trickier.

answered Apr 12, 2020 at 21:02

Rustam A.'s user avatar

Rustam A.Rustam A.

8098 silver badges15 bronze badges

I’d run into the same error. I learnt from another SO answer that you need to set the recursion limit through sys and resource modules.

answered Nov 12, 2021 at 2:30

Aravind's user avatar

1

"Segmentation fault (core dumped)" is the string that Linux prints when a program exits with a SIGSEGV signal and you have core creation enabled. This means some program has crashed.

If you’re actually getting this error from running Python, this means the Python interpreter has crashed. There are only a few reasons this can happen:

  1. You’re using a third-party extension module written in C, and that extension module has crashed.

  2. You’re (directly or indirectly) using the built-in module ctypes, and calling external code that crashes.

  3. There’s something wrong with your Python installation.

  4. You’ve discovered a bug in Python that you should report.

The first is by far the most common. If your q is an instance of some object from some third-party extension module, you may want to look at the documentation.

Often, when C modules crash, it’s because you’re doing something which is invalid, or at least uncommon and untested. But whether it’s your «fault» in that sense or not — that doesn’t matter. The module should raise a Python exception that you can debug, instead of crashing. So, you should probably report a bug to whoever wrote the extension. But meanwhile, rather than waiting 6 months for the bug to be fixed and a new version to come out, you need to figure out what you did that triggered the crash, and whether there’s some different way to do what you want. Or switch to a different library.

On the other hand, since you’re reading and printing out data from somewhere else, it’s possible that your Python interpreter just read the line "Segmentation fault (core dumped)" and faithfully printed what it read. In that case, some other program upstream presumably crashed. (It’s even possible that nobody crashed—if you fetched this page from the web and printed it out, you’d get that same line, right?) In your case, based on your comment, it’s probably the Java program that crashed.

If you’re not sure which case it is (and don’t want to learn how to do process management, core-file inspection, or C-level debugging today), there’s an easy way to test: After print line add a line saying print "And I'm OK". If you see that after the Segmentation fault line, then Python didn’t crash, someone else did. If you don’t see it, then it’s probably Python that’s crashed.

Не всегда программы в Linux запускаются как положено. Иногда, в силу разных причин программа вместо нормальной работы выдает ошибку. Но нам не нужна ошибка, нам нужна программа, вернее, та функция, которую она должна выполнять. Сегодня мы поговорим об одной из самых серьезных и непонятных ошибок. Это ошибка сегментации Ubuntu. Если такая ошибка происходит только один раз, то на нее можно не обращать внимания, но если это регулярное явление нужно что-то делать.

Конечно, случается эта проблема не только в Ubuntu, а во всех Linux дистрибутивах, поэтому наша инструкция будет актуальна для них тоже. Но сосредоточимся мы в основном на Ubuntu. Рассмотрим что такое ошибка сегментирования linux, почему она возникает, а также как с этим бороться и что делать.

Что такое ошибка сегментации?

Ошибка сегментации, Segmentation fault, или Segfault, или SIGSEGV в Ubuntu и других Unix подобных дистрибутивах, означает ошибку работы с памятью. Когда вы получаете эту ошибку, это значит, что срабатывает системный механизм защиты памяти, потому что программа попыталась получить доступ или записать данные в ту часть памяти, к которой у нее нет прав обращаться.

Чтобы понять почему так происходит, давайте рассмотрим как устроена работа с памятью в Linux, я попытаюсь все упростить, но приблизительно так оно и работает.

Допустим, в вашей системе есть 6 Гигабайт оперативной памяти, каждой программе нужно выделить определенную область, куда будет записана она сама, ее данные и новые данные, которые она будет создавать. Чтобы дать возможность каждой из запущенных программ использовать все шесть гигабайт памяти был придуман механизм виртуального адресного пространства. Создается виртуальное пространство очень большого размера, а из него уже выделяется по 6 Гб для каждой программы. Если интересно, это адресное пространство можно найти в файле /proc/kcore, только не вздумайте никуда его копировать.

Выделенное адресное пространство для программы называется сегментом. Как только программа попытается записать или прочитать данные не из своего сегмента, ядро отправит ей сигнал SIGSEGV и программа завершится с нашей ошибкой. Более того, каждый сегмент поделен на секции, в некоторые из них запись невозможна, другие нельзя выполнять, если программа и тут попытается сделать что-то запрещенное, мы опять получим ошибку сегментации Ubuntu.

Почему возникает ошибка сегментации?

И зачем бы это порядочной программе лезть, куда ей не положено? Да в принципе, незачем. Это происходит из-за ошибки при написании программ или несовместимых версиях библиотек и ПО. Часто эта ошибка встречается в программах на Си или C++. В этом языке программисты могут вручную работать с памятью, а язык со своей стороны не контролирует, чтобы они это делали правильно, поэтому одно неверное обращение к памяти может обрушить программу.

Почему может возникать эта ошибка при несовместимости библиотек? По той же причине — неверному обращению к памяти. Представим, что у нас есть библиотека linux (набор функций), в которой есть функция, которая выполняет определенную задачу. Для работы нашей функции нужны данные, поэтому при вызове ей нужно передать строку. Наша старая версия библиотеки ожидает, что длина строки будет до 256 символов. Но программа была обновлена формат записи поменялся, и теперь она передает библиотеке строку размером 512 символов. Если обновить программу, но оставить старую версию библиотеки, то при передаче такой строки 256 символов запишутся нормально в подготовленное место, а вот вторые 256 перезапишут данные программы, и возможно, попытаются выйти за пределы сегмента, тогда и будет ошибка сегментирования linux.

Что делать если возникла ошибка сегментирования?

Если вы думаете, что это ошибка в программе, то вам остается только отправить отчет об ошибке разработчикам. Но вы все-таки еще можете попытаться что-то сделать.

Например, если падает с ошибкой сегментации неизвестная программа, то мы можем решить что это вина разработчиков, но если с такой ошибкой падает chrome или firefox при запуске возникает вопрос, может мы делаем что-то не так? Ведь это уже хорошо протестированные программы.

Первое, что нужно сделать — это обновить систему до самой последней версии, возможно, был баг и его уже исправили, а может у вас установлены старые версии библиотек и обновление решит проблему. В Ubuntu это делается так:

sudo apt update
sudo apt full-upgrade

Если это не помогло, нужно обнулить настройки программы до значений по умолчанию, возможно, удалить кэш. Настройки программ в Linux обычно содержатся в домашней папке, скрытых подкаталогах с именем программы. Также, настройки и кэш могут содержаться в каталогах ~/.config и ~/.cache. Просто удалите папки программы и попробуйте снова ее запустить. Если и это не помогло, вы можете попробовать полностью удалить программу, а потом снова ее установить, возможно, какие-нибудь зависимости были повреждены:

sudo apt remove пакет_программы
sudo apt autoremove
sudo apt install пакет_программы

Если есть возможность, попробуйте установить программу из другого источника, например, не из PPA, а более старую версию, из официальных репозиториев.

Когда вы все это выполнили, скорее всего, проблема не в вашем дистрибутиве, а в самой программе. Нужно отправлять отчет разработчикам. В Ubuntu это можно сделать с помощью программы apport-bug. Обычно Ubuntu предлагает это сделать сразу, после того как программа завершилась с ошибкой сегментирования. Если же ошибка сегментирования Ubuntu встречается не в системной программе, то вам придется самим искать разработчиков и вручную описывать что произошло.

Чтобы помочь разработчикам решить проблему, недостаточно отправить им только сообщение что вы поймали Segmentation Fault, нужно подробно описать проблему, действия, которые вы выполняли перед этим, так чтобы разработчик мог их воспроизвести. Также, желательно прикрепить к отчету последние функции, которые вызывала программа (стек вызовов функций), это может очень сильно помочь разработчикам.

Рассмотрим, как его получить. Это не так уж сложно. Сначала запустите вашу программу, затем узнайте ее PID с помощью команды:

pgrep программа

Дальше запускаем отладчик gdb:

sudo gdb -q

Подключаемся к программе:

(gdb) attach ваш_pid

После подключения программа станет на паузу, продолжаем ее выполнение командой:

(gdb) continue

segfault

Затем вам осталось только вызвать ошибку:

segfault1

И набрать команду, которая выведет стек последних вызовов:

(gdb) backtrace

Вывод этой команды и нужно отправлять разработчикам. Чтобы отключиться от программы и выйти наберите:

(gdb) detach
(gdb) quit

Дальше остается отправить отчет и ждать исправления ошибки. Если вы не уверены, что ошибка в программе, можете поспрашивать на форумах. Когда у вас есть стек вызовов, уже можно попытаться, если не понять в чем проблема, то попытаться узнать, не сталкивался ли с подобной проблемой еще кто-то.

Выводы

Теперь у вас есть приблизительный план действий, что нужно делать, когда появляется ошибка сегментирования сделан дамп памяти ubuntu. Если вы знаете другие способы решить эту проблему, напишите в комментариях!

A segmentation fault, also known as a segfault, is a common error that can occur in programming languages, including Python. In this blog, we will discuss what a segmentation fault is, why it occurs, and how to troubleshoot and fix it in Python.

What is a Segmentation Fault?

A segmentation fault occurs when a program tries to access a memory location that it is not allowed to access, or when it tries to write to a read-only memory location. This can happen when a program tries to access memory that has already been freed or when it tries to access memory that is outside the bounds of an array.

In Python, segmentation faults can occur when using C extensions, which allow Python to interact with native libraries and code. These extensions can be written in C or C++ and can provide significant performance benefits to Python programs. However, if these extensions are poorly written or contain bugs, they can cause segmentation faults.

Examples of Segmentation Faults in Python

Let’s look at some examples of how segmentation faults can occur in Python.

Example 1: Accessing Invalid Memory Location

a = [1, 2, 3]
print(a[4])

In this example, we are trying to access an index that is outside the bounds of the a list. This will result in a segmentation fault because the program is trying to access memory that it is not allowed to access.

Example 2: Using C Extensions

import numpy as np
a = np.zeros((10000000,))
a[10000000] = 1

In this example, we are using the NumPy library to create a large array and then attempting to write to an index that is outside the bounds of the array. This can cause a segmentation fault because the NumPy library is implemented in C and is using C code to access memory.

Can python segmentation fault be caused due to limited memory?

Yes, a segmentation fault can be caused in Python due to limited memory. When a program runs out of memory, it can result in a segmentation fault or a memory access violation.

Let’s consider an example to illustrate this:

def create_large_list():
    lst = []
    for i in range(100000000):
        lst.append(i)
    return lst

large_list = create_large_list()

In this example, we are creating a large list with 100 million elements using the create_large_list() function. If we run this program on a machine with limited memory, such as a Raspberry Pi with only 1 GB of RAM, the program will eventually run out of memory and result in a segmentation fault.

To avoid such issues, it is important to keep track of memory usage in your Python programs and avoid creating large data structures or processing large amounts of data if your machine does not have sufficient memory. You can also use tools like memory profilers to identify memory leaks or areas of your code that are using too much memory.

Troubleshooting and Fixing Segmentation Faults

If you encounter a segmentation fault in your Python program, there are several steps you can take to troubleshoot and fix the issue:

  1. Identify the source of the segmentation fault: Use a debugger or traceback to determine which line of code is causing the segmentation fault.
  2. Check for out-of-bounds array access: Make sure that you are not trying to access memory that is outside the bounds of an array.
  3. Check for memory leaks: Make sure that you are not trying to access memory that has already been freed.
  4. Check C extensions: If you are using C extensions in your Python program, make sure they are properly written and do not contain bugs that could cause segmentation faults.
  5. Use a linter and follow best practices: Use a linter to check your code for errors and follow best practices to avoid common programming mistakes that can lead to segmentation faults.

Conclusion

In conclusion, segmentation faults can occur in Python when a program tries to access memory that it is not allowed to access. These errors can be caused by a variety of issues, including out-of-bounds array access, memory leaks, and poorly written C extensions. By following best practices and using debugging tools, you can identify and fix segmentation faults in your Python programs.

Возможно, вам также будет интересно:

  • Ошибка сдк 80040005 работа программы будет прекращена
  • Ошибка сегментирования стек памяти сброшен на диск manjaro
  • Ошибка сд карты сд карта повреждена замените ее
  • Ошибка сегментирования стек памяти сброшен на диск linux
  • Ошибка сд карты нет доступа вот блиц

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии