Main Content

Memory comparison of strings

memcmp compares data stored in strings after the null terminator

Description

This defect occurs when:

  • You compare two strings byte-by-byte with the memcmp function.

  • The number of bytes compared is such that you compare meaningless data stored after the null terminator.

For instance:

memcmp(string1, string2, sizeof(string1))
can compare bytes in the string after the null terminator.

Risk

The null terminator signifies the end of a string. Comparison of bytes after the null terminator is meaningless. You might reach the false conclusion that two strings are not equal, even if the bytes before the null terminator store the same value.

Fix

Use strcmp for string comparison. The function compares strings only up to the null terminator.

If you use memcmp for a byte-by-byte comparison of two strings, avoid comparison of bytes after the null terminator. Determine the number of bytes to compare by using the strlen function.

Examples

expand all

#include <stdio.h>
#include <string.h>

#define SIZE20 20

int func()
{
    char s1[SIZE20] =  "abc";
    char s2[SIZE20] =  "abc";

    return memcmp(s1, s2, sizeof(s1));
}

In this example, sizeof returns the length of the entire array s1, which is 20. However, only the first three bytes of the string are relevant.

Even though s1 and s2 hold the same value, the comparison with memcmp can show a false inequality.

Correction — Use strlen to Determine Number of Bytes to Compare

One possible correction is to determine the number of bytes to compare using the strlen function. strlen returns the number of bytes before the null terminator (and excluding the null terminator itself).

#include <stdio.h>
#include <string.h>

#define SIZE20 20

int func()
{
    char s1[SIZE20] =  "abc";
    char s2[SIZE20] =  "abc";

    return memcmp(s1, s2, strlen(s1));
}

Result Information

Group: Programming
Language: C | C++
Default: On for handwritten code, off for generated code
Command-Line Syntax: MEMCMP_STRINGS
Impact: Medium

Version History

Introduced in R2017a