cppcheck icon indicating copy to clipboard operation
cppcheck copied to clipboard

LCppC backport: Improved CheckStl::string_c_str()

Open PKEuS opened this issue 2 years ago • 3 comments

As a follow-up to the discussion in PR4143, I am starting to provide a few fixes/improvements from LCppC to cppcheck.

PKEuS avatar Jun 11 '22 06:06 PKEuS

It seems like this check for conversion of c_str to string should use getParentValueTypes to get the type its converted to. A simpler version could be like this:

for (const Token *tok = scope.bodyStart; tok && tok != scope.bodyEnd; tok = tok->next()) {
    if (!Token::Match(tok, ". c_str|data ( )"))
        continue;
    if (!astIsContainer(tok->astOperand2()))
        continue;
    for(const ValueType& vt:getParentValueType(tok->tokAt(2), mSettings)) {
        if (!vt.container)
            continue;
        // Warn on conversion back to string
        string_c_str(tok);
        break;
    }
}

This would most likely handle a lot more cases than the current checkers do, and is much simpler.

Now all the checks for "Dangerous usage of c_str()" can probably be removed as the lifetime checker should catch all of those.

pfultz2 avatar Jun 11 '22 15:06 pfultz2

Now all the checks for "Dangerous usage of c_str()" can probably be removed as the lifetime checker should catch all of those.

Would be nice, but it does not seem to be the case.

PKEuS avatar Jun 11 '22 16:06 PKEuS

Ah yea then we should open issues for the gaps there so we can fix the lifetime checker.

pfultz2 avatar Jun 11 '22 16:06 pfultz2