CERT.MEMCMP.FLOAT_MEMBER

The CERT.MEMCMP.FLOAT_MEMBER checker reports a defect when two structures containing floating point members are compared by using memcmp().

Vulnerability and risk

Even if the values of two floating points are equal, they might not be equivalent. So, using memcmp() directly might result in an incorrect result.

Mitigation and prevention

Structures That contain floating point objects should not be compared directly with memcmp(). Instead, the members should be compared individually to check if the floating point members are equivalent.

Vulnerable code example

Copy
  struct S {
    int a;
    float f;
  };
    
  bool comparison(const struct S *S0, const struct S *S1) {
    if (!S0 && !S1)
      return true;
    else if (!S0 || !S1)
     return false;
   return 0 == memcmp(S0, S1, sizeof(struct S));
 }

In this example, we are using memcmp() to compare structures containing floating point members. Klocwork will report a CERT.MEMCMP.FLOAT_MEMBER defect on line 11.

Fixed code example

Copy
  struct S {
    int a;
    float f;
  };
    
  bool comparison(const struct S *S0, const struct S *S1) {
    if (!S0 && !S1)
      return true;
    else if (!S0 || !S1)
     return false;
   return (S0->a == S1->a && S0->f == S1->f);
 }

In this fixed example, the code compares members of the structure individually, so Klocwork does not report a defect.