CXX.MALLOC.SIZEOF

Always call sizeof() when allocating memory with malloc

It is very important to calculate the size of the buffer when performing operations such as copying a buffer. When calculating the buffer size of an array or structure, calculating the buffer size only by considering the number of elements of the array or structure results in incorrect size calculation without considering the size of the basic data type. Also, even though the size of the data type is considered in the structure, compilers may have different results due to problems such as placement and padding. For example, for the size of a structure such as "struct {char test[3]; short test2[2];}", since char is 1-Byte and short is 2-Byte, it can be determined that (1-Byte * 3) + (2-Byte * 2) = 7-Byte, but total of 8 bytes will be allocated including padding in the 32-bit VS2013.

Mitigation and prevention

To avoid this mistake, it is correct to calculate the size using the sizeof() function (such as sizeof (struct) or sizeof (array)) rather than the size calculation being performed directly by the developer. Here, care must be taken not to perform sizeof() on the pointer when the size of the data type is calculated. The size of basic data types (char, short, int, etc.) depends on their size. On the other hand, pointers (char *, short *, int *, etc.) are all 1 word in size. The size of a pointer varies only by platform, but on the same platform (32-bit machine: 4-byte, 16-bit machine: 2-byte). In other words, calculating the size of a pointer to the size of the data type pointed to by the pointer causes a big error. Therefore, be careful not to perform sizeof() operation on pointer type. This incorrect calculation of the buffer size can lead to several vulnerabilities, including buffer overflows.

Vulnerable code example

Copy
void mc_int_009(){
    int *pi_bad = malloc(2);
    int *pi_good = malloc(2*sizeof(int));
    int *pi_good2 = malloc(sizeof(int));
}

In the example code above, an error will be reported for the pi_bad assignment because sizeof() is not used in the size calculation.