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

1  #include <memory.h>

2  struct S {
3    int x, y;
4  };
  
5  void zero_S(struct S *ps) {
6    memset(ps, 0, sizeof(ps));
7  }

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

Fixed code example

1  #include <memory.h>

2  struct S {
3     int x, y;
4  };

5  void zero_S(struct S *ps) {
7    memset(ps, 0, sizeof(*ps));     
8    memset(ps, 0, sizeof(struct S));
9  }

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