Main Content

MISRA C:2023 Rule 21.15

The pointer arguments to the Standard Library functions memcpy, memmove and memcmp shall be pointers to qualified or unqualified versions of compatible types

Since R2024a

Description

Rule Definition

The pointer arguments to the Standard Library functions memcpy, memmove and memcmp shall be pointers to qualified or unqualified versions of compatible types.

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

Rationale

The functions

memcpy( arg1, arg2, num_bytes );
memmove( arg1, arg2, num_bytes );
memcmp( arg1, arg2, num_bytes );
perform a byte-by-byte copy, move or comparison between the memory locations that arg1 and arg2 point to. A byte-by-byte copy, move or comparison is meaningful only if arg1 and arg2 have compatible types.

Using pointers to different data types for arg1 and arg2 typically indicates a coding error.

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

#include <stdint.h>

void f ( uint8_t s1[ 8 ], uint16_t s2[ 8 ] )
{
	( void ) memcpy ( s1, s2, 8 ); /* Non-compliant */
}

In this example, s1 and s2 are pointers to different data types. The memcpy statement copies eight bytes from one buffer to another.

Eight bytes represent the entire span of the buffer that s1 points to, but only part of the buffer that s2 points to. Therefore, the memcpy statement copies only part of s2 to s1, which might be unintended.

Check Information

Group: Standard libraries
Category: Required
AGC Category: Required

Version History

Introduced in R2024a