scanf Cppcheck警告 [英] scanf Cppcheck warning

查看:279
本文介绍了scanf Cppcheck警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Cppcheck对scanf显示以下警告:

Cppcheck shows the following warning for scanf:


Message: scanf without field width limits can crash with huge input data. To fix this error message add a field width specifier:
    %s => %20s
    %i => %3i

Sample program that can crash:

#include 
int main()
{
    int a;
    scanf("%i", &a);
    return 0;
}

To make it crash:
perl -e 'print "5"x2100000' | ./a.out

我无法通过键入巨大的输入数据使该程序崩溃。我应该输入什么才能导致崩溃?我也无法理解此警告中最后一行的含义:

I cannot crash this program typing "huge input data". What exactly should I type to get this crash? I also don't understand the meaning of the last line in this warning:

perl -e ...

perl -e ...

推荐答案

最后一行是运行示例命令,以演示示例程序的崩溃。实质上,这会导致perl打印2.100.000倍 5,然后将其传递到程序 a.out(它是经过编译的示例程序)的标准输入。

The last line is an example command to run to demonstrate the crash with the sample program. It essentially causes perl to print 2.100.000 times "5" and then pass this to the stdin of the program "a.out" (which is meant to be the compiled sample program).

首先, scanf()应该仅用于测试,而不是在现实世界的程序中使用,因为它不能很好地处理多个问题(例如,询问为%i,但用户输入为 12345abc( abc将保留在标准输入中,并可能导致以下输入被填充而用户没有机会对其进行更改)。

First of all, scanf() should be used for testing only, not in real world programs due to several issues it won't handle gracefully (e.g. asking for "%i" but user inputs "12345abc" (the "abc" will stay in stdin and might cause following inputs to be filled without a chance for the user to change them).

关于此问题: scanf()会知道它应该读取一个整数值,但是不知道它能持续多长时间。 16位整数,32位整数或64位整数或什至更大的值(尚不知道)带有可变数量参数的函数(用 ... )不知道传递的元素的确切数据类型,因此它必须依赖格式字符串(格式标记的原因不是C#中那样是可选的)您只在其中编号的位置,例如 {0} {1} {2} )。而且,如果没有给定的长度,则必须假定其长度也可能取决于平台(使该功能更加不易使用)。

Regarding this issue: scanf() will know it should read a integer value, however it won't know how long it can be. The pointer could point to a 16 bit integer, 32 bit integer, or a 64 bit integer or something even bigger (which it isn't aware off). Functions with a variable number of arguments (defined with ...) don't know the exact datatype of elements passed, so it has to rely on the format string (reason for the format tags to not be optional like in C# where you just number them, e.g. "{0} {1} {2}"). And without a given length it has to assume some length which might be platform dependant as well (making the function even more unsave to use).

通常,考虑一下有害的缓冲区溢出攻击的起点。如果您想保护和优化程序,请先将其替换为替代方案。

In general, consider it possibly harmful and a starting point for buffer overflow attacks. If you'd like to secure and optimize your program, start by replacing it with alternatives.

这篇关于scanf Cppcheck警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆