Skip to main content

IAR Embedded Workbench for RISC-V 3.40

MISRAC2012-Rule-21.14

In this section:
Synopsis

(Required) The Standard Library function memcmp shall not be used to compare null terminated strings. If the length of either of the two strings is less than n, then they may compare as different even when they are logically the same.

Enabled by default

Yes

Severity/Certainty

Medium/Medium

mediummedium.png
Full description

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

Coding standards
MISRA C:2012 Rule-21.14

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

Code examples

The following code example fails the check and will give a warning:

#include<stdlib.h>

extern char buffer1[ 12 ];
extern char buffer2[ 12 ];

void f1 ( void ) {
    ( void ) strcpy ( buffer1, "abc" );
    ( void ) strcpy ( buffer2, "abc" );
    /* The following use of memcmp is non-compliant */
    if ( memcmp ( buffer1, buffer2, sizeof ( buffer1 ) ) != 0 ) {
        /*
         * The strings stored in buffer1 and buffer 2 are reported to be
         * different, but this may actually be due to differences in the
         * uninitialised characters stored after the null terminators.
         */
    }
}

The following code example passes the check and will not give a warning about this issue:

#include<stdlib.h>
#include<mc3_types.h>

/* The following definition violates other guidelines */
unsigned char headerStart[ 6 ] = { 'h', 'e', 'a', 'd', 0, 164 };

void f2 ( const uint8_t *packet ) {
    /* The following use of memcmp is compliant */
    if ( ( NULL != packet ) && ( memcmp( packet, headerStart, 6 ) == 0 ) ) {
        /*
         * Comparison of values having essentially unsigned type reports that
         * contents are the same. Any null terminator is simply treated as a
         * zero value and any differences beyond it are significant.
         */
    }
}