Checkers:INCORRECT.ALLOC_SIZE

From current

Reference > C/C++ checkers > 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.

Code examples

Vulnerable code example

1  typedef struct S{
2    int a,b,c;
3  
4  }tS, *pS;
5  
6  void foo(int n) {
7    pS tmp1 = (pS) malloc(n * sizeof(pS));
8    free(tmp1);
9  }

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

External guidance