CWARN.MEMSET.SIZEOF.PTR

Memset-like function with 'sizeof' applied to pointer

The CWARN.MEMSET.SIZEOF.PTR checker flags memset-type functions in which sizeof is applied to a pointer instead of a pointed object.

Vulnerability and risk

When an incorrect size is passed to a memset function, the wrong number of bytes is filled by the call. This situation can result in weaknesses like buffer overflow.

Vulnerable code example

Copy
  #include <memory.h>
  struct S {
    int x, y;
  };
    void zero_S(struct S *ps) {
    memset(ps, 0, sizeof(ps));
  }

In this example, Klocwork flags line 5, in which sizeof is applied to the pointer ps.

Fixed code example

Copy
  #include <memory.h>
  struct S {
     int x, y;
  };
  void zero_S(struct S *ps) {
    memset(ps, 0, sizeof(*ps));     
    memset(ps, 0, sizeof(struct S));
  }

The fixed example shows two instances in lines 6 and 7, in which the code is entered correctly.