c语言scanf错误c4996,C语言常见错误杂谈(一)scanf()、scanf_s()与错误 C4996与解决方法...

错误 C4996

初学C语言时,第一个接触到的I/O函数便是scanf()了。但在高版本的 Visual Studio (包括但不限于2015、2013、2012)编译代码时,却会出现意想不到的错误。

有如下一段简单的代码:

69c5a8ac3fa60e0848d784a6dd461da6.png

#include "stdio.h"

int main(void)

{inti;

printf("Input i\n");

scanf("%d", &i);

printf("i is %d", i);return 0;

}

69c5a8ac3fa60e0848d784a6dd461da6.png

但会输出一个错误 C4996,错误信息如下

错误 1 error C4996: ‘scanf’: This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

报错说scanf不安全,推荐将scanf替换scanf_s。替换之后之后,代码如下

69c5a8ac3fa60e0848d784a6dd461da6.png

#include "stdio.h"

int main(void)

{inti;

printf("Input i\n");

scanf_s("%d", &i);

printf("i is %d", i);return 0;

}

69c5a8ac3fa60e0848d784a6dd461da6.png

便没有错误提示了。

scanf与scanf_s

在MSDN有介绍这些以_s结尾的函数,包括 scanf_s、scanf_s_l、wscanf_s、_wscanf_s_l。这些版本的函数具有安全增强功能。

scanf等函数存在于版本较旧的CRT(C runtime library, part of the C standard library)中,具有安全性问题,比如在读取字符时,若不指定%s的宽度,可能会导致缓冲区溢出。

在使用scanf时,如果规定了读取的宽度,便不会报错。将代码修改如下:

69c5a8ac3fa60e0848d784a6dd461da6.png

#include "stdio.h"

int main(void)

{inti;

printf("Input i\n");

scanf_s("%5d", &i);

printf("i is %d", i);return 0;

}

69c5a8ac3fa60e0848d784a6dd461da6.png

这里控制了读入的%d宽度为5。但是读入的数据超过宽度的限制时,便会丢失数据。比如这是输入100000,输出的i值为10000。

解决方法

1.使用scanf时规定宽度。

2.使用sacnf_s替换sacnf。

3.在新建项目的时候取消SDL检查。

286735ef5ae9c8b9848e65520b4238e8.png

本文由 whchina(江城老温)原创发布,转载请注明出处,江城老温 as a thinker。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值