Re: bad pointer exception
Chris wrote:
On Jun 17, 8:08 pm, Stuart Golodetz
<sgolod...@NdOiSaPlA.pMiPpLeExA.ScEom> wrote:
Chris wrote:
Hello.
how do you catch bad pointer dereferences in C++?
example:
#include <stdio.h>
void main()
{
try
{
int *pi;
*pi = 10;
}
catch(...)
{
printf("Exception caught \n\n");
}
}
catch handler is not executed, I get a runtime error instead.
so how?
thx
Chris
Dereferencing a bad pointer results in undefined behaviour - it doesn't
throw, so you can't catch it. You just have to make sure you don't mess
up :) If you use smart pointers (e.g. shared_ptr) instead of raw
pointers, they are sometimes checked on use (against NULL only and
generally in debug mode only), but that's about as much help as you're
likely to get. Other than that, you're pretty much on your own...
Cheers,
Stu
p.s.
1) int main()
2) #include <cstdio>
3) (Add #include <iostream> and then...) std::cout << "Exception
caught\n\n";
"Dereferencing a bad pointer results in undefined behaviour".
How can it be undefined behaviour if it generates a runtime error time
and time again?
To give you a quote from (a draft copy of) the C++ standard:
"--undefined behavior: Behavior, such as might arise upon use of an
erroneous program construct or of erroneous data, for which the
Standard imposes no requirements."
In other words, if you dereference a bad pointer, what happens is not
defined by the standard. That doesn't mean that it's not consistent
(although it may very well not be) - it does mean that the standard
itself gives you no cause to rely on the resulting behaviour.
Doesn't it just mean that, when trying to access memory that isn't
yours it should be considered as 'Access violation' ?
No, it means what it says. The practical consequences are that if you're
lucky, your program will blow up in your face with something like an
access violation. If you're not lucky, it might "just work" until you
come to show it to a client, at which point the aforementioned will then
happen.
Is there absolutely no way to prevent the program from crashing?
Of course there is - don't write bad code <g>. Not that avoiding silly
mistakes is necessarily easy, of course. The point, though, is that C++
is not a language that holds your hand while you make mistakes and
kindly points them out to you. In and of itself, that doesn't make it
either better or worse than the alternatives - what it does mean is that
if that's not acceptable to you, you need to look for a different language.
Cheers,
Stu
p.s. Incidentally, I agree that it would be nice if you could catch this
sort of error reliably in C++. I'm not one of these people who gets
excited about "programming without a safety net" - it's just the way
things are when you write in C++, rather than something to be welcomed.
In practice, I find it doesn't bite me that often these days; you get
used to it.
grtz