Integer values used as a size argument to malloc(), calloc(), realloc(), or aligned_alloc() must be valid and large enough to contain the objects to be stored. If size arguments are incorrect or can be manipulated by an attacker, then a buffer overflow may occur. Incorrect size arguments, inadequate range checking, integer overflow, or truncation can result in the allocation of an inadequately sized buffer. The programmer must ensure that size arguments to memory allocation functions allocate sufficient memory
Typically the amount of memory to allocate will be the size of the type of object to allocate. When allocating space for an array, the size of the object will be multiplied by the bounds of the array. Use the correct type of the object when computing the size of chunk to allocate.
Noncompliant Code Example (Size Calculation)
...
| CERT C Secure Coding Standard | INT31-C. Ensure that integer conversions do not result in lost or misinterpreted data INT32-C. Ensure that operations on signed integers do not result in overflow INT18-C. Evaluate integer expressions in a larger size before comparing or assigning to that size MEM04-C. Do not perform zero-length allocations EXP01-C. Do not take the size of a pointer to determine the size of the pointed-to type |
| CERT C++ Secure Coding Standard | MEM35-CPP. Allocate sufficient memory for an object |
| ISO/IEC TR 24772:2013 | Buffer Boundary Violation (Buffer Overflow) [HCB] |
| ISO/IEC TS 17961 | Taking the size of a pointer to determine the size of the pointed-to type [sizeofptr] |
| MITRE CWE | CWE-190, Integer overflow (wrap or wraparound) CWE-131, Incorrect calculation of buffer size |
...