c.lang.correctness.c-string-equality.c-string-equality

profile photo of returntocorpreturntocorp
Author
247
Download Count*

Using == on char* performs pointer comparison, use strcmp instead

Run Locally

Run in CI

Defintion

rules:
  - id: c-string-equality
    patterns:
      - pattern: (char *$X) == (char *$Y)
      - metavariable-comparison:
          metavariable: $X
          comparison: $X != 0
      - metavariable-comparison:
          metavariable: $Y
          comparison: $Y != 0
    message: Using == on char* performs pointer comparison, use strcmp instead
    fix: strcmp($X, $Y) == 0
    languages:
      - c
    severity: ERROR
    metadata:
      category: correctness
      technology:
        - c
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

c-string-equality.c

#include <stddef.h>
#include <string.h>

int main()
{
    char *s = "Hello";

    // ruleid:c-string-equality
    if (s == "World") {
        return -1;
    }

    // ok:c-string-equality
    if (strcmp(s, "World") == 0) {
        return 1;
    }

    // ok:c-string-equality
    if (!strcmp(s, "World")) {
        return 1;
    }

    // ok:c-string-equality
    if (s == 0) {
      return 1;
    }

    // ok:c-string-equality
    if (NULL == s) {
      return 1;
    }

    return 0;
}