using exceptions to catch segmentation faults?

Discussion in 'C++' started by Digital Puer, Dec 27, 2005.

  1. Digital Puer

    Digital Puer Guest

    Hi, I'm coming over from Java to C++, so please bear with me.
    In C++, is there a way for me to use exceptions to catch
    segmentation faults (e.g. when I access a location off
    the end of an array)?

    Thanks.
     
    Digital Puer, Dec 27, 2005
    #1
    1. Advertising

  2. Digital Puer wrote:
    > Hi, I'm coming over from Java to C++, so please bear with me.
    > In C++, is there a way for me to use exceptions to catch
    > segmentation faults (e.g. when I access a location off
    > the end of an array)?
    >
    > Thanks.


    It is implementation dependent; standard says nothing of it. If you're
    trying to find an equivalent to Java 's run-time exception by catching
    Throwable, then you can try something like this, but it's NOT
    guaranteed be caught - thus you can still suffer from segmentation
    fault or bus error in form of unexpected program abort.

    try
    {
    //access invalid memory location.
    }catch(...)
    {
    std::cerr<<"something bad happened\n"
    }
    -----------------
    catch(...) -- is somewhat equivalent to catch(throwable), beware the
    implementation detail and read on compiler vendor provisions regarding
    it.


    Best,
     
    puzzlecracker, Dec 27, 2005
    #2
    1. Advertising

  3. Digital Puer

    John Carson Guest

    "Digital Puer" <> wrote in message
    news:
    > Hi, I'm coming over from Java to C++, so please bear with me.
    > In C++, is there a way for me to use exceptions to catch
    > segmentation faults (e.g. when I access a location off
    > the end of an array)?


    If you use vectors instead of arrays and use the at() member function rather
    than the subscript operator, an exception is thrown for out of range
    accesses. There is, however, no general C++ exception mechanism for
    segmentation faults.

    Windows has "structured exceptions" in addition to C++ exceptions. These
    structured exceptions do include segmentation faults (or "access violations"
    as they are more commonly called). Other platforms may have similar
    facilities, but I don't know about them.


    --
    John Carson
     
    John Carson, Dec 27, 2005
    #3
  4. Digital Puer

    Guest

    , Dec 27, 2005
    #4
  5. Digital Puer

    Digital Puer Guest

    John Carson wrote:
    > "Digital Puer" <> wrote in message
    > news:
    > > Hi, I'm coming over from Java to C++, so please bear with me.
    > > In C++, is there a way for me to use exceptions to catch
    > > segmentation faults (e.g. when I access a location off
    > > the end of an array)?

    >
    > If you use vectors instead of arrays and use the at() member function rather
    > than the subscript operator, an exception is thrown for out of range
    > accesses. There is, however, no general C++ exception mechanism for
    > segmentation faults.
    >


    Thank you for the info about vector::at. I looked through the docs
    on vector, but there doesn't seem to be an analogous 'setter'
    function for vector that can throw an exception. Is that right?
    All I can find are append functions (e.g. push_back). I would
    like 'data[12] = foo' to throw an exception if it's past the end.
     
    Digital Puer, Dec 27, 2005
    #5
  6. Digital Puer

    John Carson Guest

    "Digital Puer" <> wrote in message
    news:
    > John Carson wrote:
    >> "Digital Puer" <> wrote in message
    >> news:
    >>> Hi, I'm coming over from Java to C++, so please bear with me.
    >>> In C++, is there a way for me to use exceptions to catch
    >>> segmentation faults (e.g. when I access a location off
    >>> the end of an array)?

    >>
    >> If you use vectors instead of arrays and use the at() member
    >> function rather than the subscript operator, an exception is thrown
    >> for out of range accesses. There is, however, no general C++
    >> exception mechanism for segmentation faults.
    >>

    >
    > Thank you for the info about vector::at. I looked through the docs
    > on vector, but there doesn't seem to be an analogous 'setter'
    > function for vector that can throw an exception. Is that right?
    > All I can find are append functions (e.g. push_back). I would
    > like 'data[12] = foo' to throw an exception if it's past the end.


    at is overloaded to be both a getter and a setter function (just like the
    subscript operator is). Thus you can use

    data.at(12) = foo;

    Note that range errors are relative to the value returned by size(), not the
    value returned by capacity(), e.g.,

    vector<int> vec;
    vec.reserve(1);
    try
    {
    vec.at(0) = 2;
    }
    catch (exception &e)
    {
    cout << "Caught: " << e.what( ) << endl;
    cout << "Type: " << typeid( e ).name( ) << endl;
    };

    will throw an exception because size() returns 0 so the index is >= size().
    However

    vector<int> vec;
    vec.resize(1);
    try
    {
    vec.at(0) = 2;
    }
    catch (exception &e)
    {
    cout << "Caught: " << e.what( ) << endl;
    cout << "Type: " << typeid( e ).name( ) << endl;
    };

    does not throw an exception because size() is 1 and so the index is <
    size().

    --
    John Carson
     
    John Carson, Dec 27, 2005
    #6
  7. Digital Puer wrote:
    > Hi, I'm coming over from Java to C++, so please bear with me.
    > In C++, is there a way for me to use exceptions to catch
    > segmentation faults (e.g. when I access a location off
    > the end of an array)?


    such mechanisms are platform specific and there is some good reason why
    they have not been incooperated into the c++ language itself, for
    example:

    - common out-of-bounds errors often do not trigger a segfault because
    your program has to access non-mapped or foreign memory for that to
    happen. small off-bounds errors may pass unnoticed.
    - writing into memory off bounds that your process owns will invoke
    undefined behaviour and may wreak havoc.
    - your process might have been corrupted on OS side before the
    segmentation fault occured anyways.

    in c++ you should always ensure that memory operations are valid and
    use related tools like checked array index access, smart pointers and
    the like if you need language support to do so.

    if you are still interested into handling segfaults have a look into
    platform specific newsgroups for more details.

    -- peter
     
    peter steiner, Dec 27, 2005
    #7
  8. Digital Puer wrote:
    > Hi, I'm coming over from Java to C++, so please bear with me.
    > In C++, is there a way for me to use exceptions to catch
    > segmentation faults (e.g. when I access a location off
    > the end of an array)?


    It useless. After a segmentation fault, at least on unix, the behavior
    of the process is undefined. You can not reliably handle or recover
    from it. I see no reason why this wouldn't apply for windoze.

    http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html
    ....
    The behavior of a process is undefined after it ignores a SIGFPE,
    SIGILL, SIGSEGV, or SIGBUS signal that was not generated by kill(),
    sigqueue(), or raise().
    ....
     
    Maxim Yegorushkin, Dec 27, 2005
    #8
  9. Digital Puer

    Ron Natalie Guest

    Digital Puer wrote:
    > Hi, I'm coming over from Java to C++, so please bear with me.
    > In C++, is there a way for me to use exceptions to catch
    > segmentation faults (e.g. when I access a location off
    > the end of an array)?
    >
    > Thanks.
    >

    I have no clue what you mean by your allusion to Java. Segementation
    faults are a foreign concept to Java as well. There's no portable
    way of catching them in C++ (and in many implementations there's no
    good way to catch them at all). There's no indication that accessing
    off the end of an array generates a segmentation fault either. Chances
    are you just access/clobber some other piece of memory.
     
    Ron Natalie, Dec 27, 2005
    #9
  10. Digital Puer

    John Carson Guest

    "Maxim Yegorushkin" <> wrote in message
    news:
    > Digital Puer wrote:
    >> Hi, I'm coming over from Java to C++, so please bear with me.
    >> In C++, is there a way for me to use exceptions to catch
    >> segmentation faults (e.g. when I access a location off
    >> the end of an array)?

    >
    > It useless. After a segmentation fault, at least on unix, the behavior
    > of the process is undefined. You can not reliably handle or recover
    > from it. I see no reason why this wouldn't apply for windoze.


    It doesn't apply. Of course a segmentation fault normally indicates a
    program bug, so it is doubtful if the program can continue successfully from
    that point on. However, it is certainly not the case that the behaviour of
    the process becomes undefined as a matter of course.

    For example, the following crashes on Windows:

    int main()
    {
    int *ptr = 0;
    *ptr = 2;

    return 0;
    }

    However, using structure exception handling, we can do this:

    int main()
    {
    int *ptr = 0;

    __try
    {
    *ptr = 2;
    }
    __except(EXCEPTION_EXECUTE_HANDLER)
    {
    cout << "exception thrown\n";
    }

    // code execution resumes here and the process is in a
    // completely robust state.

    return 0;
    }

    The details of structured exception handling are described in Jeffrey
    Richter's book, Programming Applications for Microsoft Windows.


    --
    John Carson
     
    John Carson, Dec 27, 2005
    #10
  11. Digital Puer

    Guest

    > In C++, is there a way for me to use exceptions to catch
    > segmentation faults (e.g. when I access a location off
    > the end of an array)?


    Please consider this article.
    http://en.wikipedia.org/wiki/Segmentation_fault

    You get this error if any instruction in the code "attempts to access a
    memory location in a way it is not allowed to". How much do you trust
    your environment if it was tried to read or overwrite the value at an
    unexpected address?
    Is the infrastructure and mechanism for exception handling still
    working after this kind of programming error was detected?
    Should a direct program abort be the prefered reaction in this case so
    that the error context can be analysed from a core dump file by a
    debugger?
    http://lambdacs.com/debugger/USENIX/Debugger_USENIX_2003.html
    (Omniscient Debugging)

    http://en.wikipedia.org/wiki/Buffer_overflow
    How much effort do you put on a code structure with guarantees that out
    of range accesses can not happen?

    Regards,
    Markus
     
    , Dec 27, 2005
    #11
  12. Digital Puer

    Guest

    > In C++, is there a way for me to use exceptions to catch
    > segmentation faults (e.g. when I access a location off
    > the end of an array)?


    Please consider this article.
    http://en.wikipedia.org/wiki/Segmentation_fault

    You get this error if an instruction in the code "attempts to access a
    memory location in a way it is not allowed to". How much do you trust
    your environment if it was tried to read or overwrite the value at an
    unexpected address?
    Is the infrastructure and mechanism for exception handling still
    working after this kind of programming error was detected?
    Should a direct program abort be the prefered reaction in this case so
    that the error context can be analysed from a core dump file by a
    debugger?
    http://lambdacs.com/debugger/USENIX/Debugger_USENIX_2003.html
    (Omniscient Debugging)

    Can your program safely continue its execution if an
    "access_violation_exception" will be caught?
    Can any further damage from unexpected or undefined behaviour be
    restricted?

    How much effort do you put on a code structure with guarantees that out
    of range accesses can not happen?
    - http://en.wikipedia.org/wiki/Static_code_analysis
    - http://en.wikipedia.org/wiki/Buffer_overflow

    Regards,
    Markus
     
    , Dec 27, 2005
    #12
  13. Digital Puer

    Digital Puer Guest

    Ron Natalie wrote:
    > Digital Puer wrote:
    > > Hi, I'm coming over from Java to C++, so please bear with me.
    > > In C++, is there a way for me to use exceptions to catch
    > > segmentation faults (e.g. when I access a location off
    > > the end of an array)?
    > >
    > > Thanks.
    > >

    > I have no clue what you mean by your allusion to Java. Segementation
    > faults are a foreign concept to Java as well. There's no portable
    > way of catching them in C++ (and in many implementations there's no
    > good way to catch them at all). There's no indication that accessing
    > off the end of an array generates a segmentation fault either. Chances
    > are you just access/clobber some other piece of memory.



    In Java, accessing an array beyond its allocated length generates
    an exception. Since on my system (linux w/g++) accessing an
    array beyond its allocation generally results in a seg fault, I am
    trying to catch it with an exception handler to tell me where
    the fault occurred.
     
    Digital Puer, Dec 27, 2005
    #13
  14. Digital Puer

    Digital Puer Guest

    Maxim Yegorushkin wrote:
    > Digital Puer wrote:
    > > Hi, I'm coming over from Java to C++, so please bear with me.
    > > In C++, is there a way for me to use exceptions to catch
    > > segmentation faults (e.g. when I access a location off
    > > the end of an array)?

    >
    > It useless. After a segmentation fault, at least on unix, the behavior
    > of the process is undefined. You can not reliably handle or recover
    > from it. I see no reason why this wouldn't apply for windoze.
    >
    > http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html
    > ...
    > The behavior of a process is undefined after it ignores a SIGFPE,
    > SIGILL, SIGSEGV, or SIGBUS signal that was not generated by kill(),
    > sigqueue(), or raise().
    > ...



    I'm not trying to recover from the seg fault. I just want to find out
    where in the code it happened.
     
    Digital Puer, Dec 27, 2005
    #14
  15. Digital Puer

    Old Wolf Guest

    Digital Puer wrote:
    >>> Hi, I'm coming over from Java to C++, so please bear with me.
    >>> In C++, is there a way for me to use exceptions to catch
    >>> segmentation faults


    No

    > I'm not trying to recover from the seg fault. I just want to find out
    > where in the code it happened.


    Even if it were possible, it would still not tell you where in the code
    the error happened. When you catch an exception, all you know
    is that it occurred somewhere inside the corresponding try-block.
    So unless you were planning to wrap EVERY statement in a
    try..catch block, you're out of luck.

    It sounds like you are looking for a program that will tell you
    when you access memory that you shouldn't. This is normally
    called "a debugger" and there are lots of those available (valgrind
    is one that springs to mind).
     
    Old Wolf, Dec 27, 2005
    #15
  16. Digital Puer wrote:

    >
    > Ron Natalie wrote:
    >> Digital Puer wrote:
    >> > Hi, I'm coming over from Java to C++, so please bear with me.
    >> > In C++, is there a way for me to use exceptions to catch
    >> > segmentation faults (e.g. when I access a location off
    >> > the end of an array)?
    >> >
    >> > Thanks.
    >> >

    >> I have no clue what you mean by your allusion to Java. Segementation
    >> faults are a foreign concept to Java as well. There's no portable
    >> way of catching them in C++ (and in many implementations there's no
    >> good way to catch them at all). There's no indication that accessing
    >> off the end of an array generates a segmentation fault either. Chances
    >> are you just access/clobber some other piece of memory.

    >
    >
    > In Java, accessing an array beyond its allocated length generates
    > an exception. Since on my system (linux w/g++) accessing an
    > array beyond its allocation generally results in a seg fault, I am
    > trying to catch it with an exception handler to tell me where
    > the fault occurred.

    Enable core-files and examine them with a debugger.

    To enable core-files enter "ulimit -c unlimited". When your program
    segfaults it generates a file named core or core.$PID. Start gdb with 2
    arguments: the first is your program and the second is the core-file. In
    gdb enter "where" and you get a nice stacktrace. It will be even nicer if
    you compile your program with -g (and don't use -O or -O2 or something).

    Tommi
     
    Tommi =?UTF-8?B?TcOka2l0YWxv?=, Dec 27, 2005
    #16
  17. Digital Puer

    Guest

    > The details of structured exception handling are described in Jeffrey
    > Richter's book, Programming Applications for Microsoft Windows.


    See also:
    Article "A Crash Course on the Depths of Win32™ Structured Exception
    Handling"
    by Matt Pietrek
    Microsoft Systems Journal (January 1997)
    http://www.microsoft.com/msj/0197/exception/exception.aspx

    Regards,
    Markus
     
    , Dec 28, 2005
    #17
  18. Digital Puer

    Guest

    > In Java, accessing an array beyond its allocated length generates
    > an exception. Since on my system (linux w/g++) accessing an
    > array beyond its allocation generally results in a seg fault, I am
    > trying to catch it with an exception handler to tell me where
    > the fault occurred.


    I guess that the compiler should be corrected. Would you like to create
    a bug report?
    http://gcc.gnu.org/bugzilla/
    http://en.wikipedia.org/wiki/GCJ

    Do you find it under the known errors altready?

    Regards,
    Markus
     
    , Dec 28, 2005
    #18
  19. Digital Puer

    Ron Natalie Guest

    Digital Puer wrote:
    > Ron Natalie wrote:
    >> Digital Puer wrote:
    >>> Hi, I'm coming over from Java to C++, so please bear with me.
    >>> In C++, is there a way for me to use exceptions to catch
    >>> segmentation faults (e.g. when I access a location off
    >>> the end of an array)?
    >>>
    >>> Thanks.
    >>>

    >> I have no clue what you mean by your allusion to Java. Segementation
    >> faults are a foreign concept to Java as well. There's no portable
    >> way of catching them in C++ (and in many implementations there's no
    >> good way to catch them at all). There's no indication that accessing
    >> off the end of an array generates a segmentation fault either. Chances
    >> are you just access/clobber some other piece of memory.

    >
    >
    > In Java, accessing an array beyond its allocated length generates
    > an exception.


    But not a segmentation fault.

    >Since on my system (linux w/g++) accessing an
    > array beyond its allocation generally results in a seg fault,


    Sorry, but that's not true. What causes a segmentation fault is
    accessing a piece of memory that's restricted (either not mapped,
    or mapped for read only and you are trying to write it). Since
    memory is allocated in chunks, and array allocations are interleaved
    with other memory objects, the chances are unless you have a totally
    wild subscript (much larger than the end), you won't get a segmentation
    fault directly from the access.

    As others pointed out C (and hence by inheritance C++) does no range
    checking on it's arrays. You can use a different object in C++
    (such as vector) to provide that. There are also packages out there
    that instrument C++ in certain ways to do the check (at a substantial
    performance penalty) to do these checks.

    Your initial premise is wrong (that an array index error necessarily
    generates a segmentation fault in C++) and there is no way to detect
    either one.
     
    Ron Natalie, Dec 28, 2005
    #19
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Mathias

    Segmentation faults using threads

    Mathias, Feb 13, 2007, in forum: Python
    Replies:
    8
    Views:
    326
    John Nagle
    Feb 14, 2007
  2. Stanley S
    Replies:
    16
    Views:
    2,554
    Keith Thompson
    Dec 22, 2005
  3. ZillionDollarSadist

    Segmentation faults on "new"

    ZillionDollarSadist, Jan 17, 2007, in forum: C++
    Replies:
    6
    Views:
    373
    Jacek Dziedzic
    Jan 18, 2007
  4. George Sakkis

    Debugging segmentation faults

    George Sakkis, Mar 7, 2007, in forum: Python
    Replies:
    4
    Views:
    394
    John Nagle
    Mar 8, 2007
  5. Kaspar Schiess

    YAML custom load: Segmentation faults

    Kaspar Schiess, Jun 25, 2004, in forum: Ruby
    Replies:
    2
    Views:
    144
    Kaspar Schiess
    Jun 25, 2004
Loading...

Share This Page