This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 24.5.2 - The C++ Standard Library functions memcpy, memmove and memcmp from
<cstring> shall not be used
[cstring.syn]
Category: Required
Analysis: Decidable, Single Translation Unit
Amplification
These functions shall not be called or have their addresses taken, and no macro having one of these names shall be expanded.
Note: this rule also applies to the same functions from <string.h>.
Rationale
Use of memmove and memcpy can result in undefined behaviour if the blocks of memory pointed to by their pointer
parameters:
- Overlap (
memcpy only); or
- Are potentially-overlapping; or
- Are not trivially copyable.
Additionally, memcmp may not indicate equality for objects that are logically equal. Specifically:
- Floating point values may not compare equal, as the floating point format allows multiple representations for some values, such as zero and
minus zero (which will not compare equal); and
- Class objects may not compare equal due to:
- Padding between members, as its content is unspecified and effectively indeterminate; or
- Unions having different active members or members of different sizes.
- Buffers may not compare equal when the meaningful content does not occupy the whole buffer and the whole buffer is compared. For example, this
may happen with:
-
std::vector, where memory is preallocated to enable efficient growth; or
- C-style strings, where the
\0 terminator may occur within the buffer and be followed by irrelevant data.
Example
void f1( const uint8_t * src, uint8_t * dst, size_t len )
{
memmove( dst, src, len ); // Non-compliant
}
struct S
{
bool m1;
// There may be padding here
int64_t m2;
};
void f2( S s1, S s2 )
{
if ( memcmp( &s1, &s2, sizeof( S ) ) != 0 ) // Non-compliant
{
}
};
extern char buffer1[ 12 ];
extern char buffer2[ 12 ];
void f3()
{
strcpy( buffer1, "abc" ); // Indeterminate contents in elements 4 to 11
strcpy( buffer2, "abc" ); // Indeterminate contents in elements 4 to 11
if ( memcmp( buffer1, buffer2, sizeof( buffer1 ) ) != 0 ) // Non-compliant
{
}
}
Copyright The MISRA Consortium Limited © 2023