Main Content

MISRA C:2023 Rule 21.14

The Standard Library function memcmp shall not be used to compare null terminated strings

Since R2024a

Description

Rule Definition

The Standard Library function memcmp shall not be used to compare null terminated strings.

This rule comes from MISRA C™: 2012 Amendment 1.

Rationale

If memcmp is used to compare two strings and the length of either string is less than the number of bytes compared, the strings can appear different even when they are logically the same. The characters after the null terminator are compared even though they do not form part of the string.

For instance:

memcmp(string1, string2, sizeof(string1))
can compare bytes after the null terminator if string1 is longer than string2.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

extern char buffer1[ 12 ];
extern char buffer2[ 12 ];
void f1(void)
{
    (void) strcpy(buffer1, "abc");
    (void) strcpy(buffer2, "abc");

    if (memcmp(buffer1,    /* Non-compliant */
               buffer2,
               sizeof(buffer1)) != 0) {

    }
}

In this example, the comparison in the if statement is noncompliant. The strings stored in buffer1 and buffer2 can be reported different, but this difference comes from uninitialized characters after the null terminators.

Check Information

Group: Standard libraries
Category: Required
AGC Category: Required

Version History

Introduced in R2024a