Handling SIGSEGV Signal

Ξ May 9th, 2008 | → 0 Comments |
Development |, , , , |

Soon or later, your Linux developed C/C++ code will generate a SISEGV signal and your application will miserably crash. This signal is generated when a program tries to read or write outside the memory that is allocated for it, or to write memory that can only be read. (Actually, the signals only occur when the program goes far enough outside to be detected by the system’s memory protection mechanism.) The name is an abbreviation for “segmentation violation”.

In order to improve your program, and terminate in a controlled way, you can register a custom function to handle such signal. The following example shows the leave function that is called whenever a SIGSEGV signal is launched.

    #include

    #include

    void leave( int s ) {
        std::cout << "FATAL: Leaving due to SIGSEGV." << std::endl;
        exit( s );
    }

    int main() {
        // Register SIGSEGV handler!
        signal( SIGSEGV, leave );

        // originate a SIGSEGV
        double array[20];
        std::cout << array[10000] << std::endl;

        return 0;

    }

 

On the nightstand...


    The Art of Agile Development


    Beautiful Architecture


    Modern C++ Design


    Large Scale C++ Software Design

Personal

Friends


Interesting


Shared Readings