为什么memcpy_s比memcpy安全

memcpy_s在安全性上优于memcpy,因为它会检查参数是否为空指针、内存拷贝大小是否超过限制,防止缓冲区溢出,以及源目标对象是否重叠,避免了潜在的安全风险。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

void* memcpy( void *dest, const void *src, size_t count );
(until C99)
void* memcpy( void *restrict dest, const void *restrict src, size_t count );
(since C99)
errno_t memcpy_s( void *restrict dest, rsize_t destsz,
                  const void *restrict src, rsize_t count );
(2) (since C11)



1) Copies count characters from the object pointed to by src to the object pointed to by dest. Both objects are interpreted as arrays of unsigned char.
 The behavior is undefined if access occurs beyond the end of the dest array. If the objects overlap (which is a violation of the restrict contract) (since C99), the behavior is undefined. The behavior is undefined if eitherdest or src is a null pointer.
2) Same as (1), except that the following errors are detected at runtime and cause the entire destination range [dest, dest+destsz) to be zeroed out (if both dest and destsz are valid), as well as call the currently installed constraint handler function:
  • dest or src is a null pointer
  • destsz or count is greater than RSIZE_MAX
  • count is greater than destsz (buffer overflow would occur)
  • the source and the destination objects overlap
 The behavior is undefined if the size of the character array pointed to by dest < count <= destsz; in other words, an erroneous value of destsz does not expose the impending buffer overflow.
As all bounds-checked functions, memcpy_s is only guaranteed to be available if __STDC_LIB_EXT1__ is defined by the implementation and if the user defines __STDC_WANT_LIB_EXT1__ to the integer constant 1before including string.h.

相较于memcpy,memcpy_s会检查:
1) dest、src的合法性;
2)检查destsz、count的合法性;
3)检查缓存异常的风险;
4)检查目的buf和源buf是否存在内存覆盖。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值