Search code examples
pythonsegmentation-faultgtk3pygobject

using "try" to avoiding a segmentation fault


Recently in one of my programs I got a segmentation fault problem. I managed to find the line that its is causing the problem but I haven't find the way of fixing it.

the line:

self.window_player.add(self.vlc)

where self.vlc is a widget and self.window_player is an empty Gtk.Window() created in glade.

The line is at the __init__ of my program, so actually this problem only happen when launching the program. The weird fact is that the error only appears like 1 of 10 times (of launching the program)

the error: Segmentation fault is the only output that I get from the terminal

So I tried:

while True:
    try:
        self.window_player.add(self.vlc)
        break
    except:
        print "segmentation"

The problem is that the segmentation fault don't seems to be excepted by the try!


Solution

  • Sorry, you can't handle it. A segfault is caused by memory corruption, reading or writing beyond boundaries of owned memory, double frees, and a few other.

    You can found a few examples of issues that cause a segfault here:

    https://gist.github.com/carlos-jenkins/8873932

    The operating system will kill the offending program, you can't do much about it. Your only solution is to correct the root problem.

    You can run a program using the tool Valgrind, it will allow you to find exactly where the problem is:

    http://valgrind.org/

    On Ubuntu, just sudo apt-get install valgrind and then valgrind <program cmd> will launch the program. This offcourse will be a lot slower, but will identify the problem most of the time.

    Side note: Technically you can catch a SIGSEV signal by registering a callback for this signal. But you shouldn't. See this answer for more information:

    https://stackoverflow.com/a/10203062/439494