C & C++

C & C++

By DeepSource

Possibly missing sizeof() in memory allocation CXX-S1006

Security

The malloc function usually expects a memory size value in units (usually byte) when allocating any type. Use sizeof(type) * number_of_values as the size argument for malloc to avoid making mistakes.

It is a good practice to use sizeof(type) with malloc and other memory allocation functions because many types can have variable size in bytes depending on the platform used.

For instance, many of the default integer types in C & C++ such as, 'int', are platform-dependent.

Bad practice

int* ints = (int*)malloc(64);

Recommended

int* ints = (int*)malloc(sizeof(int) * 16);

References