关于strcpy和strcpy_s安全方面比较问题?

在VS的CRT中,增加了一些具有更强安全性的CRT函数,例如strcpy_s, strncat_s等。

(MSDN: <Security Enhancements in the CRT >

Significant enhancements have been made to make the CRT more secure. Many CRT functions now have more secure versions. If a new secure function exists, the older, less secure version is marked as deprecated and the new version has the _s ("secure") suffix.

It should be noted that in this context, "deprecated" just means that a function's use is not recommended; it does not indicate that the function is scheduled to be removed from the CRT.

It should also be noted that the secure functions do not prevent or correct security errors; rather, they catch errors when they occur. They perform additional checks for error conditions, and in the case of an error, they invoke an error handler (see Parameter Validation).

For example, the strcpy function has no way of telling if the string that it's copying is too big for its destination buffer. However, its secure counterpart, strcpy_s, takes the size of the buffer as a parameter, so it can determine if a buffer overrun will occur. If you usestrcpy_s to copy eleven characters into a ten-character buffer, that is an error on your part;strcpy_s cannot correct your mistake, but it can detect your error and inform you by invoking the invalid parameter handler.



文章大致翻译加结合自己的想法,不赞同的地方请留言评论:

MSDN:<CRT中的安全增强功能>
已经进行了显着的增强以使得CRT更加安全。许多CRT功能现在有更安全的版本。如果存在新的安全函数,则旧的较不安全的版本将标记为已弃用,新版本将具有_s(“secure”)后缀。
应该注意,在这个上下文中,“不推荐”仅仅意味着不推荐使用函数;它不表示该功能被安排从CRT中删除。
还应当注意,安全功能不防止或纠正安全错误;相反,它们在发生错误时捕获错误。它们对错误条件执行额外的检查,并且在发生错误的情况下,它们调用错误处理程序(请参阅参数验证)。
例如,strcpy函数没有办法告诉它复制的字符串对于它的目标缓冲区是否太大。但是,它的安全副本strcpy_s将缓冲区的大小作为参数,因此它可以确定是否会发生缓冲区溢出。如果使用strcpy_s将十一个字符复制到一个十字符缓冲区中,那就是一个错误;strcpy_s无法更正您的错误,但它可以检测您的错误,并通过调用无效的参数处理程序通知您。

下面是使用strcpy_s与strcpy的安全性比较

 char szBuf[2] = {0};

 strcpy_s(szBuf, 2, "12131");  //新的CRT函数
 strcpy(szBuf,  "12131");    //老的CRT函数

上述代码,明显有缓冲区溢出的问题。 使用strcpy_s函数则会抛出一个异常。而使用strcpy函数的结果则未定,因为它错误地改变了程序中其他部分的内存的数据,可能不会抛出异常但导致程序数据错误,也可能由于非法内存访问抛出异常。

使用新的增强安全的CRT函数有什么好处呢?简单地说,新的函数加强了对参数合法性的检查以及缓冲区边界的检查,如果发现错误,会返回errno或抛出异常。老版本的这些CRT函数则没有那么严格的检查与校验,如果错误地传输了参数或者缓冲区溢出,那么错误并不能被立刻发现,对于定位程序错误也带来更大困难。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值