Re: bad pointer exception
Chris <cmrchs@gmail.com> writes:
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.
If your compiler is able to compile the above code and does not choke on
void main(), then it can probably achieve anything.
For a conforming implementation, however, you should enable an
appropriate warning level and expect/hope that the compiler will pick up
such coding errors. For instance:
19:13:04 Paul Bibbings@JIJOU
/cygdrive/D/CPPProjects/CLCPP $cat catch_error.cpp
#include <cstdio> // prefer over <stdio.h>
int main()
{
try
{
int *pi;
*pi = 10;
}
catch(...)
{
printf("Exception caught\n");
}
}
19:13:12 Paul Bibbings@JIJOU
/cygdrive/D/CPPProjects/CLCPP $i686-pc-cygwin-gcc-4.4.3 -ansi
-pedantic -Wall -c catch_error.cpp
catch_error.cpp: In function ??int main()??:
catch_error.cpp:9: warning: ??pi?? is used uninitialized in this
function
If you leave until runtime then dereferencing pi might or might not
produce a runtime error, depending on what address the junk value of pi
contains.
In short, don't allow such an oversight to remain in executing code, and
get your compiler to help you.
Regards
Paul Bibbings