Possible misuse of sizeof
Use of sizeof operator can cause unintended
results
Description
This defect occurs
when Polyspace®
Bug Finder™ detects possibly unintended results from
the use of sizeof operator. For instance:
You use the
sizeofoperator on an array parameter name, expecting the array size. However, the array parameter name by itself is a pointer. Thesizeofoperator returns the size of that pointer.You use the
sizeofoperator on an array element, expecting the array size. However, the operator returns the size of the array element.The size argument of certain functions such as
strncmporwcsncpyis incorrect because you used thesizeofoperator earlier with possibly incorrect expectations. For instance:In a function call
strncmp(string1, string2, num),numis obtained from an incorrect use of thesizeofoperator on a pointer.In a function call
wcsncpy(destination, source, num),numis the not the number of wide characters but a size in bytes obtained by using thesizeofoperator. For instance, you usewcsncpy(destination, source, sizeof(destination) - 1)instead ofwcsncpy(destination, source, (sizeof(desintation)/sizeof(wchar_t)) - 1).
Risk
Incorrect use of the sizeof operator can
cause the following issues:
If you expect the
sizeofoperator to return array size and use the return value to constrain a loop, the number of loop runs are smaller than what you expect.If you use the return value of
sizeofoperator to allocate a buffer, the buffer size is smaller than what you require. Insufficient buffer can lead to resultant weaknesses such as buffer overflows.If you use the return value of
sizeofoperator incorrectly in a function call, the function does not behave as you expect.
Fix
Possible fixes are:
Do not use the
sizeofoperator on an array parameter name or array element to determine array size.The best practice is to pass the array size as a separate function parameter and use that parameter in the function body.
Use the
sizeofoperator carefully to determine the number argument of functions such asstrncmporwcsncpy. For instance, for wide string functions such aswcsncpy, use the number of wide characters as argument instead of the number of bytes.
Examples
Result Information
| Group: Programming |
| Language: C | C++ |
| Default: On for handwritten code, off for generated code |
Command-Line Syntax: SIZEOF_MISUSE |
| Impact: High |
Version History
Introduced in R2015b
See Also
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)