Fix #10993 danglingTemporaryLifetime reported in two different locati… (#4462)

* Fix #10993 danglingTemporaryLifetime reported in two different locations for std::string_view usage

* Missing include

* Add test
This commit is contained in:
chrchr-github 2022-09-14 07:28:04 +02:00 committed by GitHub
parent 07caf17eb3
commit 266174ddc4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 21 additions and 1 deletions

View File

@ -392,6 +392,13 @@ void CheckAutoVariables::errorUselessAssignmentPtrArg(const Token *tok)
"Assignment of function parameter has no effect outside the function. Did you forget dereferencing it?", CWE398, Certainty::normal);
}
bool CheckAutoVariables::diag(const Token* tokvalue)
{
if (!tokvalue)
return true;
return !mDiagDanglingTemp.insert(tokvalue).second;
}
//---------------------------------------------------------------------------
static bool isInScope(const Token * tok, const Scope * scope)
@ -603,7 +610,8 @@ void CheckAutoVariables::checkVarLifetimeScope(const Token * start, const Token
break;
} else if (!tokvalue->variable() &&
isDeadTemporary(mTokenizer->isCPP(), tokvalue, tok, &mSettings->library)) {
errorDanglingTemporaryLifetime(tok, &val, tokvalue);
if (!diag(tokvalue))
errorDanglingTemporaryLifetime(tok, &val, tokvalue);
break;
}
}

View File

@ -27,6 +27,7 @@
#include "errortypes.h"
#include <string>
#include <set>
class Settings;
class Token;
@ -127,6 +128,11 @@ private:
"- suspicious assignment of pointer argument\n"
"- useless assignment of function argument\n";
}
/** returns true if tokvalue has already been diagnosed */
bool diag(const Token* tokvalue);
std::set<const Token*> mDiagDanglingTemp;
};
/// @}
//---------------------------------------------------------------------------

View File

@ -2744,6 +2744,12 @@ private:
" return sv;\n"
"}\n");
ASSERT_EQUALS("", errout.str());
check("void f() {\n" // #10993
" std::string_view v = std::string();\n"
" v.data();\n"
"}\n");
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:2] -> [test.cpp:3]: (error) Using object that is a temporary.\n", errout.str());
}
void danglingLifetimeUniquePtr()