#include <stdio.h>
...
int age;
float height;
char name[50];
printf("请输入年龄、身高、姓名:");
scanf("%d %f %s", &age, &height, name);
printf("年龄:%d,身高:%.1f,姓名:%s\n", age, height, name);
- 在 C 语言开发中,执行上述代码,报如下错误
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_s
若要禁用此弃用警告,请使用 _CRT_SECURE_NO_WARNINGS
查看在线帮助以获取详细信息
问题原因
-
scanf 函数不会检查输入缓冲区的大小,容易导致缓冲区溢出
-
编译器推荐使用安全的
scanf_s
函数,它对于字符串输入,需要额外指定缓冲区大小
处理策略
- 使用推荐的
scanf_s
函数
#include <stdio.h>
#include <stdlib.h>
...
int age;
float height;
char name[50];
printf("请输入年龄、身高、姓名:");
scanf_s("%d %f %s", &age, &height, name, (unsigned)_countof(name));
printf("年龄:%d,身高:%.1f,姓名:%s\n", age, height, name);
- 禁用安全警告
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
...
int age;
float height;
char name[50];
printf("请输入年龄、身高、姓名:");
scanf("%d %f %s", &age, &height, name);
printf("年龄:%d,身高:%.1f,姓名:%s\n", age, height, name);