Main Content

Expensive use of string functions from the C standard library

String functions from the C standard library are used inefficiently

Since R2022a

Description

This defect occurs when any of these conditions are true:

  • You use strcmp() or strlen() 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() or strlen(). 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

expand all

#include <cstring>


int isEmpty(const char* pszName)
{
   return strcmp(pszName, "") == 0; //Defect
}

int isEmpty2(const char* pszName)
{
   return strlen(pszName) == 0;  //Defect
}

In this example, Polyspace® flags the use of string functions strcmp() and strlen() to check for empty C- strings. Checking for empty C-strings is not the intended use of these functions. Such use of these functions results in inefficient and unnecessarily complex code.

Correction — Check for Empty C-String by Comparing First Character to '\0'

Instead of using the string functions, it is more efficient to check for empty C-strings by comparing the first character of the string to null or '\0'. This method reduces the function overhead and makes the code more efficient.

#include <cstring>


int isEmpty(const char* pszName)
{
   return *pszName == 0; 
}
#include <string.h>

void foo(void){
	char* str;
	//...
	strcpy(str,"");
	//...
}

In this example, a C-string is cleared by copying an empty string into it. Calling strcpy to clear a C-string is unnecessary and makes the code inefficient.

Correction

To clear a C-string, assign null or '\0' to the string.

#include <string.h>

void foo(void){
	char* str;
	//...
	*str = '\0';
	//...
}

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