INCORRECT.ALLOC_SIZE

Incorrect allocation size

The INCORRECT.ALLOC_SIZE checker finds situations in which a malloc, calloc, or realloc function is called to allocate memory and the size of the memory allocated is less than intended. This often happens when a sizeof keyword is used to specify the size of the memory to be allocated. Instead of using the actual type as the argument of the sizeof operator, the pointer of the type is mistakenly used, causing sizeof to return the size of pointer (which is 4 in a 32-bit platform).

Vulnerability and risk

This situation can cause less memory to be allocated than intended, resulting in unexpected problems like buffer overflow.

Vulnerable code example

Copy
  typedef struct S{
    int a,b,c;
  
  }tS, *pS;
  
  void foo(int n) {
    pS tmp1 = (pS) malloc(n * sizeof(pS));
    free(tmp1);
  }

Klocwork flags line 7, in which the sizeof keyword is incorrectly applied to pointer ps.

Security training

Application security training materials provided by Secure Code Warrior.