In maintaining a large legacy code base I came across this function which serves as an accessor to an XML tree.
std::string DvCfgNode::getStringValue() const
{
xmlChar *val = xmlNodeGetContent(mpNode);
if (val == 0)
return 0;
std::string value = (const char *)val;
xmlFree(val);
return value;
}
How can this function return '0'? In C you could return a zero pointer as char * indicating no data was found, but is this possible in C++ with std::string? I wouldn't think so but not knowledgable enough with C++.
The (10 year old) code compiles and runs under C++ 98.
EDIT I
Thanks to everyone for the comments. To answer a few questions:
a) Code is actually 18 years old and about, umm, 500K-1M lines (?)
b) exception handling is turned on, but there are no try-catch blocks anywhere except for a few in main(), which result in immediate program termination.
c) Poor design in the calling code which seems to "trust" getStringValue() to return a proper value, so lots of something like:
std::string s = pTheNode->getStringValue()
Probably just lucky it never returned zero (or if it did, nobody found the bug until now).
xmlNodeGetContent(mpNode)has obviously 2 reasons to returnNULL. One, being that there is no content. The other being that the system is out of memory. If you fix the semantics of the function, for example by having it returnstd::optional<std::string>to express that there is not always a value, you still have to worry about the out of memory condition, which might need another form of addressing in this particular code base.