...
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. When allocating space for a structure containing a flexible array member, the size of the array member must be added to the size of the structure (see MEM33-C. Allocate and copy structures containing a flexible array member dynamically). Use the correct type of the object when computing the size of memory to allocate.
STR31-C. Guarantee that storage for strings has sufficient space for character data and the null terminator is a specific instance of this rule.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
| CERT C Secure Coding Standard | ARR01-C. Do not apply the sizeof operator to a pointer when taking the size of an array 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. Beware of zero-length allocationsVOID EXP01-C. Do not take the size of a pointer to determine the size of the pointed-to type |
| ISO/IEC TR 24772:2013 | Buffer Boundary Violation (Buffer Overflow) [HCB] |
| ISO/IEC TS 17961:2013 | Taking the size of a pointer to determine the size of the pointed-to type [sizeofptr] |
| MITRE CWE | CWE-131, Incorrect Calculation of Buffer Size CWE-190, Integer Overflow or Wraparound) CWE-467, Use of sizeof() on a Pointer Type |
Bibliography
| [Coverity 2007] | |
| [Drepper 2006] | Section 2.1.1, "Respecting Memory Bounds" |
| [Seacord 2013] | Chapter 4, "Dynamic Memory Management" Chapter 5, "Integer Security" |
| [Viega 2005] | Section 5.6.8, "Use of sizeof() on a Pointer Type" |
| [xorl 2009] | CVE-2009-0587: Evolution Data Server Base64 Integer Overflows |
...