Skip to content

Commit

Permalink
StringCompareRule: add NULL check
Browse files Browse the repository at this point in the history
  • Loading branch information
jcdkiki committed May 14, 2024
1 parent f922e1a commit 0748849
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
8 changes: 8 additions & 0 deletions examples/ex-string-compare/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ void wide_strings()
wchar_t str1[32] = L"Hello";
wchar_t *str2 = wcsdup(L"World");

if (str2 == NULL) {
abort();
}

if (str1 == str2) {
puts("One");
}
Expand Down Expand Up @@ -40,6 +44,10 @@ void compare_const_and_not_const()
{
char *str = (char*)malloc(1024 * sizeof(char));

if (str == NULL) {
abort();
}

scanf("%1023s", str);
if (str == "Bad!") {
puts("Something");
Expand Down
8 changes: 7 additions & 1 deletion rules/StringCompareRule.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include "oclint/AbstractASTVisitorRule.h"
#include "oclint/RuleConfiguration.h"
#include "oclint/RuleSet.h"
#include "clang/Basic/Specifiers.h"
#include <iostream>

namespace oclint {
Expand Down Expand Up @@ -83,6 +84,11 @@ namespace oclint {
return type->isAnyCharacterType() || type.getAsString() == "wchar_t";
}

bool IsNull(clang::Expr *expr)
{
return expr->isNullPointerConstant(*this->_carrier->getASTContext(), clang::Expr::NPC_ValueDependentIsNotNull);
}

const char *OpcodeAsString(Opcode opcode)
{
switch (opcode) {
Expand All @@ -105,7 +111,7 @@ namespace oclint {
clang::Expr *left = binop->getLHS();
clang::Expr *right = binop->getRHS();

if (IsString(left) || IsString(right))
if (!IsNull(left) && !IsNull(right) && (IsString(left) || IsString(right)))
addViolation(binop, this, std::string("comparing 2 strings by using ") + OpcodeAsString(opcode) + ".");

return true;
Expand Down

0 comments on commit 0748849

Please sign in to comment.