CERT.MEMCMP.PADDED_DATA

When you use the memcmp() function between two objects, it will compare the padding bytes and not compare the contents. It is only meaningful to use for copying object with no padding. The CERT.MEMCMP.PADDED_DATA checker looks for padding data in the objects being compared by using the memcmp() function.

Vulnerability and risk

The memcmp() function does a byte-by-byte comparison. Such a comparison between structures can give incorrect results.

Mitigation and prevention

To avoid this problem, each of the fields of a structure with padding data should be compared manually.

Vulnerable code example

Copy
  #include <string.h>
  
  struct s {
    char c;
    int i;
    char buffer[13];
  };
  
  void compare0(const struct s *left, const struct s *right) {
   if ((left && right) &&
       (0 == memcmp(left, right, sizeof(struct s)))) {
     /* ... */
   }
 }

Klocwork reports a CERT.MEMCMP.PADDED_DATA issue at line 12 where the memcmp() function is used to compare the contents of two structures that includes padding data.

Fixed code example

Copy
   <codeblock >
   #include <string.h>
   
   struct s {
     char c;
     int i;
     char buffer[13];
   };
     
  void compare1(const struct s *left, const struct s *right) {
    if ((left && right) &&
        (left->c == right->c) &&
        (left->i == right->i) &&
        (0 == memcmp(left->buffer, right->buffer, 13))) {
      /* ... */
    }
  }

In this fixed example, the issue is avoided because the comparison for all the fields is done manually, so there is no longer any padding byte comparison.