主要内容

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

自 R2024a 起

描述

规则定义

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

此规则来自 MISRA C™:2012 Amendment 1。

理由

函数

memcpy( arg1, arg2, num_bytes );
memmove( arg1, arg2, num_bytes );
memcmp( arg1, arg2, num_bytes );
会在 arg1arg2 所指向的内存位置之间逐字节地进行复制、移动或比较操作。只有当 arg1arg2 具有兼容的类型时,逐字节复制、移动或比较才有意义。

arg1arg2 使用指向不同数据类型的指针通常指示存在编码错误。

故障排除

如果您预期会出现违规,但未看到该违规,请参阅诊断为何编码规范违规未按预期显示

示例

全部展开

#include <stdint.h>

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

在此示例中,s1s2 是指向不同数据类型的指针。memcpy 语句将 8 个字节从一个缓冲区复制到另一个缓冲区。

8 个字节代表 s1 所指向缓冲区的整个范围,但仅占 s2 所指向缓冲区的一部分。因此,memcpy 语句仅将 s2 的一部分复制到 s1,这可能并非预期操作。

检查信息

组:标准库
类别:必需
AGC 类别:必需

版本历史记录

在 R2024a 中推出


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace® Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.