Improper Size Calculation¶
Rule ID¶
MI104
Definition¶
The software does not correctly calculate the size to be used when allocating a buffer, which could lead to a buffer overflow.
Example¶
See one of the applicable code examples from CWE.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
The following code allocates memory for a maximum number of widgets. It then gets a user-specified number of widgets, making sure that the user does not request too many. It then initializes the elements of the array using InitializeWidget(). Because the number of widgets can vary for each request, the code inserts a NULL pointer to signify the location of the last widget. However, this code contains an off-by-one calculation error (CWE-193). It allocates exactly enough space to contain the specified number of widgets, but it does not include the space for the NULL pointer. As a result, the allocated buffer is smaller than it is supposed to be (CWE-131). So if the user ever requests MAX_NUM_WIDGETS, there is an out-of-bounds write (CWE-787) when the NULL is assigned. Depending on the environment and compilation settings, this could cause memory corruption.
References¶
- Common Weakness Enumeration: CWE-131