473,385 Members | 1,844 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

exceptions with null pointers

Hello,
in the following code i have segmentaion fault instead of exception.
Why? What i must to do to catch exceptions in such situation? Used
compiler: gcc version 3.3.6 (Debian 1:3.3.6-13)

int main()
{
try{
int* p = NULL;
*p = 4;
}
catch(...){
cout << "exception" << endl;
}
return 0;
}

Thanks,
Denis.

Jul 25 '06 #1
18 2941
Denis Petronenko wrote:
in the following code i have segmentaion fault instead of exception.
Why? What i must to do to catch exceptions in such situation? Used
compiler: gcc version 3.3.6 (Debian 1:3.3.6-13)

int main()
{
try{
int* p = NULL;
*p = 4;
}
catch(...){
cout << "exception" << endl;
}
return 0;
}
Dereferencing a null pointer produces *undefined behaviour*. It
may (allowed to) throw an exception, or it may send a nasty e-mail
to your supervisor and then reformat your hard drive. Expecting
something *definite* from a construct that has undefined behaviour
is silly.

You can't do anything certain to catch an exception. Even if you
figure something out about your system/compiler which will lead you
to a solution, it won't work on a different system or compiler, and
therefore cannot be classified as a C++ solution. A simple answer
to this is, "check your pointer for being null before dereferencing".

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 25 '06 #2
Denis Petronenko <pe********@gmail.comwrote:
in the following code i have segmentaion fault instead of exception.
there is nothing in the language that says "dereferencing null pointer
will invode exception". If you need language with this sort of
warranties, switch to C# or Java. What actually happens in C++ (and C)
in such situation is undefined behaviour, which means program is free to
do anything (sending insults to your boss included).
Why? What i must to do to catch exceptions in such situation?
There is nothing you can do and keep your program portable. If you want
answer specific to your OS, ask again on another group. Dereferencing
null pointer is programming error, and fixing programming errors
(instead of hiding them) is usually best solution to erratic program
behaviour.
B.

Jul 25 '06 #3
Denis Petronenko wrote:
in the following code i have segmentaion fault instead of exception.
Why? What i must to do to catch exceptions in such situation? Used
compiler: gcc version 3.3.6 (Debian 1:3.3.6-13)

int main()
{
try{
int* p = NULL;
*p = 4;
}
catch(...){
cout << "exception" << endl;
}
return 0;
}
Dereferencing a null pointer does not throw an exception; it causes
undefined behavior, which could be a crash, a corruption of memory, or
the emptying of your bank account -- it's really undefined. Some
compilers have extensions (such as Microsoft's "structured exception
handling") that can translate such errors into exceptions, but these
are not standard.

If you want an exception, do this:

struct MyException : std::exception
{
virtual const char* what() const
{ return "My exception happened"; }
};

int main()
{
try{
int* p = NULL;
if( !p ) throw MyException();
*p = 4;
}
catch( const std::exception& e ){
cout << "exception:" << e.what() << endl;
}
return 0;
}

Cheers! --M

Jul 25 '06 #4
Denis Petronenko wrote:
in the following code i have segmentaion fault instead of exception.
Why? What i must to do to catch exceptions in such situation?
This situation does not produce exceptions and was never supposed to produce
exceptions. There's nothing to catch here.

What you have below produces undefined behavior, which leads to so called
"segmentaion fault" on your platform.
Used
compiler: gcc version 3.3.6 (Debian 1:3.3.6-13)

int main()
{
try{
int* p = NULL;
*p = 4;
}
catch(...){
cout << "exception" << endl;
}
return 0;
}
Jul 25 '06 #5

Denis Petronenko wrote:
Hello,
in the following code i have segmentaion fault instead of exception.
Why? What i must to do to catch exceptions in such situation? Used
compiler: gcc version 3.3.6 (Debian 1:3.3.6-13)

int main()
{
try{
int* p = NULL;
*p = 4;
}
catch(...){
cout << "exception" << endl;
}
return 0;
}
As others have said, no exception is thrown by *0. However, you can
create or use a "smart pointer" that could. I don't know if boost's
versions do. You could write your own but there are a lot of gotchas
that even I don't know (I'm not advanced but I have a little
experience), I've done it but I've also run into problems with my
implementations.

Jul 25 '06 #6

Denis Petronenko wrote:
Hello,
in the following code i have segmentaion fault instead of exception.
Why? What i must to do to catch exceptions in such situation? Used
compiler: gcc version 3.3.6 (Debian 1:3.3.6-13)

int main()
{
try{
int* p = NULL;
*p = 4;
}
catch(...){
cout << "exception" << endl;
}
return 0;
}


if you work exclusively on Windows using the microsoft compilers,
you will get an exception.
It is very unclear to me, why on most other systems I'm aware of this
results in a signal.
A exception is considerable more useful than a signal.
I'm not certain whether it is defined to throw an exception from a
signal handler.
You can try whether this works.
First you need to set a signal handler using the signal() function for
the matching signal.
In this handler throw an exception.
I'm not sure whether this works -- try and report your results here.

Jul 25 '06 #7

Denis Petronenko wrote:
Hello,
in the following code i have segmentaion fault instead of exception.
Why? What i must to do to catch exceptions in such situation? Used
compiler: gcc version 3.3.6 (Debian 1:3.3.6-13)

int main()
{
try{
int* p = NULL;
*p = 4;
}
catch(...){
cout << "exception" << endl;
}
return 0;
}


if you work exclusively on Windows using the microsoft compilers,
you will get an exception.
It is very unclear to me, why on most other systems I'm aware of this
results in a signal.
A exception is considerable more useful than a signal.
I'm not certain whether it is defined to throw an exception from a
signal handler.
You can try whether this works.
First you need to set a signal handler using the signal() function for
the matching signal.
In this handler throw an exception.
I'm not sure whether this works -- try and report your results here.

Jul 25 '06 #8
Peter wrote:
Denis Petronenko wrote:
>Hello,
in the following code i have segmentaion fault instead of exception.
Why? What i must to do to catch exceptions in such situation? Used
compiler: gcc version 3.3.6 (Debian 1:3.3.6-13)

int main()
{
try{
int* p = NULL;
*p = 4;
}
catch(...){
cout << "exception" << endl;
}
return 0;
}

if you work exclusively on Windows using the microsoft compilers,
you will get an exception.
It is very unclear to me, why on most other systems I'm aware of this
results in a signal.
Because it is much more efficient. If processor faults can throw
exceptions the compiler has no way of limiting which parts of the
code can throw an exception. Therefore Microsoft's compilers need
to generate code to keep track of stack unwind information dynamically
which causes run time overhead.
A exception is considerable more useful than a signal.
Exceptions are of not much use for processor faults because it is
almost impossible to write code that is exception safe against those
exceptions. You will end up terminating the program anyway.
I'm not certain whether it is defined to throw an exception from a
signal handler.
This is a _bad_ idea that is almost guaranteed to fail since it would
introduce the possibility of exceptions at arbitrary machine instructions
which the optimized static unwind information cannot handle.

Jul 25 '06 #9
Peter <pe****@xpedion.comwrote:
>int main()
{
try{
int* p = NULL;
*p = 4;
}
catch(...){
cout << "exception" << endl;
}
return 0;
}
if you work exclusively on Windows using the microsoft compilers,
you will get an exception.
Not true. C++ exception handling mechanism in Visual C++ is indeed based
on "native" exception support provided by the operating system, called
structured exception handling (SEH), or "C exceptions" (as they were
introduced long time ago as an extension to C language). These are
exceptions thrown by the operating system, eg. when invalid memory
address is accessed, division by zero happens etc.. But there are number
of optimizations that compiler applies to code when so called
"synchronous exception handling mode" is set (which is default) and,
unless you switch to "asynchronous exception handling mode", there is no
warranty that catch (...) will actually catch any SEH exceptions. This
is only visible in optimized builds, so whoever learn about the compiler
mechanics only playing with debugger in Debug builds, probably never
noticed it. It's documented in more detail here:
http://msdn2.microsoft.com/en-us/library/5skw957f.aspx and
http://msdn2.microsoft.com/en-US/library/1deeycx5.aspx

Also, in Visual C++ 2005 (msvc8) "synchronous exception mode" (default,
as it is in older versions), catch(...) will not handle any SEH at all
and will only catch C++ exceptions.
A exception is considerable more useful than a signal.
not really.
B.

Jul 26 '06 #10

Markus Schoder wrote:
Peter wrote:
I'm not certain whether it is defined to throw an exception from a
signal handler.

This is a _bad_ idea that is almost guaranteed to fail since it would
introduce the possibility of exceptions at arbitrary machine instructions
which the optimized static unwind information cannot handle.
Where would it unwind to? The signal handler is outside the main
execution path of the program. It is called by the OS when something
goes wrong and/or a signal is sent to the process. I don't think there
is anywhere for the exception to go but up into the OS...and what would
IT do about it?

Jul 26 '06 #11

Markus Schoder wrote:
Peter wrote:
Denis Petronenko wrote:
if you work exclusively on Windows using the microsoft compilers,
you will get an exception.
It is very unclear to me, why on most other systems I'm aware of this
results in a signal.

Because it is much more efficient. If processor faults can throw
exceptions the compiler has no way of limiting which parts of the
code can throw an exception. Therefore Microsoft's compilers need
to generate code to keep track of stack unwind information dynamically
which causes run time overhead.

the microsoft compiler for 64bit Windows does create code which relies
on static location-based tables for exception handling.

>
A exception is considerable more useful than a signal.

Exceptions are of not much use for processor faults because it is
almost impossible to write code that is exception safe against those
exceptions. You will end up terminating the program anyway.

nope.
E.g. you're using memory mapped io for sparse files a memory access can
generate a segmentation fault if the disk runs out of space.
Having this as an exception is considerable more useful.
Also in other cases not terminating in case of a zero pointer access is
useful inside an interactive application. The user will know that his
last action caused a zero pointer access so repeating it would probably
do the same. But at least he can gracefully shutdown the application.

>
I'm not certain whether it is defined to throw an exception from a
signal handler.

This is a _bad_ idea that is almost guaranteed to fail since it would
introduce the possibility of exceptions at arbitrary machine instructions
which the optimized static unwind information cannot handle.
Did anybody test for this?

Jul 26 '06 #12

Noah Roberts wrote:
Markus Schoder wrote:
This is a _bad_ idea that is almost guaranteed to fail since it would
introduce the possibility of exceptions at arbitrary machine instructions
which the optimized static unwind information cannot handle.

Where would it unwind to? The signal handler is outside the main
execution path of the program. It is called by the OS when something
goes wrong and/or a signal is sent to the process. I don't think there
is anywhere for the exception to go but up into the OS...and what would
IT do about it?

it is possible to return from a signal handler to the instruction which
caused it.
So the signal handler is called like any other function.

Jul 26 '06 #13

Bronek Kozicki wrote:
A exception is considerable more useful than a signal.

not really.

if you think like that you did not understand one of the two methods,
exception handling or signal handling.

Signal handling is happening up the stack -- a function is called.
Returning from this function does execute the failed instruction again.
People use such sick methods like setjmp/longjmp to hack around this
problem.

Exception Handling is happening down the stack -- the stack is being
unwound.
Exception Handling allows you to abort a complex operation and report
rich error information to the caller -- who may be expecting this
exception zero or more levels up the stack.
I avoid the expression "handler" since it can be confused with signal
handling.

Jul 26 '06 #14

Peter wrote:
Noah Roberts wrote:
Markus Schoder wrote:
This is a _bad_ idea that is almost guaranteed to fail since it would
introduce the possibility of exceptions at arbitrary machine instructions
which the optimized static unwind information cannot handle.
Where would it unwind to? The signal handler is outside the main
execution path of the program. It is called by the OS when something
goes wrong and/or a signal is sent to the process. I don't think there
is anywhere for the exception to go but up into the OS...and what would
IT do about it?


it is possible to return from a signal handler to the instruction which
caused it.
No, it isn't. You can catch the signal, deal and deal with it so you
don't crash, then instruction will continue where the PC is, but you
can't return from a signal handler like you are thinking.
So the signal handler is called like any other function.
No, it isn't.

Jul 26 '06 #15

Peter wrote:
This is a _bad_ idea that is almost guaranteed to fail since it would
introduce the possibility of exceptions at arbitrary machine instructions
which the optimized static unwind information cannot handle.

Did anybody test for this?

I did and it terminate() is being called.
It would be a major improvement if this would be possible.

Jul 26 '06 #16
Peter <pe****@xpedion.comwrote:
Bronek Kozicki wrote:
>>A exception is considerable more useful than a signal.

not really.


if you think like that you did not understand one of the two methods,
exception handling or signal handling.
you are right and I wrote the opposite I intended to
B.
--
Remove -trap- when replying. Usun -trap- gdy odpisujesz.
Aug 1 '06 #17
In VC it is possible to convert SEH exceptions into C++ exceptions - so
in theory you could create a InvalidMemoryAccessException class or a
DivideByZeroException class - anything that is handled by SEH. These
classes could then derive from std::exception if required.
This is a nice feature and I dont believe similar functionality is
supported under UNIX - so not exactly a portable solution.
Wrapping the pointers in a smart pointer and throwing an exception on
dereferencing to null is a quite simple solution to implement.
Another approach I like which is rarely used is the null reference
approach, which is especially useful with virtual inheritance. In this
approach you have a single static NULL instance of a class which you
assign (akin to a null pointer). The advantage of this is that you can
put diagnostics and logging into the NULL class.
Smart pointer appraoch is quick and probably best.

Bronek Kozicki wrote:
Peter <pe****@xpedion.comwrote:
int main()
{
try{
int* p = NULL;
*p = 4;
}
catch(...){
cout << "exception" << endl;
}
return 0;
}
if you work exclusively on Windows using the microsoft compilers,
you will get an exception.

Not true. C++ exception handling mechanism in Visual C++ is indeed based
on "native" exception support provided by the operating system, called
structured exception handling (SEH), or "C exceptions" (as they were
introduced long time ago as an extension to C language). These are
exceptions thrown by the operating system, eg. when invalid memory
address is accessed, division by zero happens etc.. But there are number
of optimizations that compiler applies to code when so called
"synchronous exception handling mode" is set (which is default) and,
unless you switch to "asynchronous exception handling mode", there is no
warranty that catch (...) will actually catch any SEH exceptions. This
is only visible in optimized builds, so whoever learn about the compiler
mechanics only playing with debugger in Debug builds, probably never
noticed it. It's documented in more detail here:
http://msdn2.microsoft.com/en-us/library/5skw957f.aspx and
http://msdn2.microsoft.com/en-US/library/1deeycx5.aspx

Also, in Visual C++ 2005 (msvc8) "synchronous exception mode" (default,
as it is in older versions), catch(...) will not handle any SEH at all
and will only catch C++ exceptions.
A exception is considerable more useful than a signal.

not really.
B.
Aug 1 '06 #18
Peter wrote:
First you need to set a signal handler using the signal() function for
the matching signal.
In this handler throw an exception.
If a signal handler doesn't exit the application, then the only thing
you are allowed to do is set a flag of type "volatile sig_atomic_t"
and return. Setting any other variable, or calling any standard
library function, causes undefined behaviour.

Returning from a signal of type SIGFPE, SIGILL, SIGSEGV, or
any other signal from an implementatation-defined list, causes
undefined behaviour. Returning from other signals causes execution
to resume from where it was interrupted.

Aug 1 '06 #19

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
by: dkcpub | last post by:
I'm very new to Python, but I couldn't find anything in the docs or faq about this. And I fished around in the IDLE menus but didn't see anything. Is there a tool that can determine all the...
6
by: Amadeus W.M. | last post by:
Does strtol raise any exceptions? Thanks!
822
by: Turamnvia Suouriviaskimatta | last post by:
I 'm following various posting in "comp.lang.ada, comp.lang.c++ , comp.realtime, comp.software-eng" groups regarding selection of a programming language of C, C++ or Ada for safety critical...
11
by: Tamas Demjen | last post by:
I was shocked to learn that VC++ 2005 Beta 2 can't catch Access Violation exceptions in unmanaged code. To reproduce this, I created a minimal Win32 console application: #include "stdafx.h" ...
4
by: Steve | last post by:
I have read a couple articles online, read my Jesse Liberty book but I am still confused as to just what the best practices are for using exceptions. I keep changing how I'm working with them and...
4
by: praviarun | last post by:
I found that the following code catches exception on gcc 4.0 i.e it prints "caught standard exception" try{ vector<inttest; test.at(0); // this line throws an exception } catch(...)
6
by: Marvin Barley | last post by:
I have a class that throws exceptions in new initializer, and a static array of objects of this type. When something is wrong in initialization, CGI program crashes miserably. Debugging shows...
0
debasisdas
by: debasisdas | last post by:
NOTE:- ========= 1.Exceptions can be declared only in the declarative part of a PL/SQL block, subprogram, or package. 2.Exception and variable declarations are similar. But remember, an...
14
by: jalqadir | last post by:
The constructor in MyClass instantiates many objects pointers through 'new', I would like to implement a way to make sure that the object has been allocated in memory by catch(ing) the bad_alloc...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.