Re: bad pointer exception
Chris <cmrchs@gmail.com> wrote in news:7fd9a323-9935-4fd2-887d-
d598c2196624@i28g2000yqa.googlegroups.com:
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?
This is not excluded by undefined behavior. Anything can happen. Runtime
error is a lot better than some quiet misbehave, but it's not guaranteed.
Doesn't it just mean that, when trying to access memory that isn't
yours it should be considered as 'Access violation' ?
The problem is that you have an uninitialized pointer. It can point to
whatever, in particular to some other variable in your code, and in this
case it would produce no access violation at all (only a silent change in
the value of your other variable).
This is the zero-overhead principle of C and C++. If this does not fit
you, you ought to choose some other language.
Is there absolutely no way to prevent the program from crashing?
Sure there is. Fix the code to have no undefined behavior.
Regards
Paavo