Mistakes during checking if a returned value is null

This is a bit modified real word example, found by tool for static analysis. In this code, foo() is a function that returns pointer to std::string or null pointer.

std::cout << foo()->length() << std::endl;

There's obvious bug here: executing length() method on value returned by foo() without checking if this variable is not null. At first it looks that it could be fixed in below way:

if (foo()) {
    std::cout << foo()->length() << std::endl;
}

Unfortunately above code is also invalid because it can't be sure that if a function once returned not null value, then it will returns it next time. This may be fixed in below way, where temporary variable was used to check if length() may be executed on variable retured by foo().

std::string* fooObj = foo();
if (fooObj) {
    std::cout << fooObj->length() << std::endl;
}

0 commentaires:

Post a Comment