diff --git a/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp --- a/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp @@ -20,11 +20,18 @@ namespace bugprone { void SuspiciousMemsetUsageCheck::registerMatchers(MatchFinder *Finder) { - // Note: void *memset(void *buffer, int fill_char, size_t byte_count); + // Match the standard memset: + // void *memset(void *buffer, int fill_char, size_t byte_count); + auto MemsetDecl = + functionDecl(hasName("::memset"), + hasParameter(0, hasType(pointerType(pointee(voidType())))), + hasParameter(1, hasType(isInteger())), + hasParameter(2, hasType(isInteger()))); + // Look for memset(x, '0', z). Probably memset(x, 0, z) was intended. Finder->addMatcher( callExpr( - callee(functionDecl(hasName("::memset"))), + callee(MemsetDecl), hasArgument(1, characterLiteral(equals(static_cast('0'))) .bind("char-zero-fill")), unless( @@ -36,14 +43,14 @@ // Look for memset with an integer literal in its fill_char argument. // Will check if it gets truncated. - Finder->addMatcher(callExpr(callee(functionDecl(hasName("::memset"))), + Finder->addMatcher(callExpr(callee(MemsetDecl), hasArgument(1, integerLiteral().bind("num-fill")), unless(isInTemplateInstantiation())), this); // Look for memset(x, y, 0) as that is most likely an argument swap. Finder->addMatcher( - callExpr(callee(functionDecl(hasName("::memset"))), + callExpr(callee(MemsetDecl), unless(hasArgument(1, anyOf(characterLiteral(equals( static_cast('0'))), integerLiteral()))), diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone-suspicious-memset-usage.cpp b/clang-tools-extra/test/clang-tidy/checkers/bugprone-suspicious-memset-usage.cpp --- a/clang-tools-extra/test/clang-tidy/checkers/bugprone-suspicious-memset-usage.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone-suspicious-memset-usage.cpp @@ -75,3 +75,8 @@ // despite v == 0. memset(p, -1, v); } + +void *memset(int); +void NoCrash() { + memset(1); +}