C++ exception error messages 选项
时间:2010-09-25 来源:蓝天寂寞
I frequently see (and I'll admit to writing it myself sometimes) error
detection code which does something along these lines:
if(badness) {
std::ostringstream err;
err << "Badness " << errcode << " has occurred while frobbing"
<< " nitzes. blah blah blah";
throw SomeException(err.str().c_str());
}
or just using snprintf:
if(badness) {
char errc[1024];
snprintf(errc, 1024, "badness %d occurred ...", errcode);
throw SomeException(errc);
}
Yet, of course, by the time we get to a:
catch(const SomeException& se) { ... }
clause somewhere up the call stack, the above stack has unwound. In the
first case, the std::string from err.str() has had its destructor run,
so our saved pointer is bogus; in the latter, there's no destructor for
char* of course but the 'errc' array is "gone".
Consider:
void X() {
try {
Y();
} catch(const SomeException& se) {
std::cerr << se.what() << "\n";
}
}
void Y() {
Z();
}
void Z() {
if(badness) { ... /* as above */ }
}
'se' stores a pointer to, say 'errc' (second case). This is probably
fine, because 'errc' is technically still around. Still, I no longer
"own" 'errc'. If things were changed and the stack for 'Y' or 'Z' was
gigantic for some reason, the operating system might presumably sbrk()
or something to shrink the stack size and reclaim the memory (granted, I
don't think this would happen w/ any OS/C++ runtime I use, but I'm
asking if this would be legal), no? In that case, accessing the pointer
stored in 'errc' would lead to a segmentation fault.
What have I misinterpreted?
Thanks,
-tom