Expensive use of string functions from the C standard library
Description
This defect occurs when any of these conditions are true:
You use
strcmp()
orstrlen()
to check if a C-string is empty.You use
strcpy()
to clear an existing C- string.
Risk
When determining if a C-string is empty, it is not efficient to compare its length to
zero by using strlen()
or compare the C-string to an empty string
(""
) by using strcmp()
. The function
strlen()
checks the entire C-string until it finds a null, which is
inefficient when checking if a C-string is empty. Invoking these functions to check for
empty C-strings is inefficient and might result in unnecessary function call
overhead.
Similarly, using strcpy()
to clear a C-string is unnecessary.
Fix
To fix this defect:
When checking if a C-string is empty, avoid using
strcmp()
orstrlen()
. Instead, compare the first character of the C-string to'\0'
.When clearing a C-string, avoid using
strcpy()
. Instead, assign the'\0'
character to the C-string.
Performance improvements might vary based on the compiler, library implementation, and environment that you are using.
Examples
Result Information
Group: Performance |
Language:C | C++ |
Default: Off |
Command-Line Syntax:
EXPENSIVE_USE_OF_C_STRING_API |
Impact: Low |
Version History
Introduced in R2022a
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)