簡體   English   中英

沒有字段寬度限制的 scanf() 可能會因大量輸入數據而崩潰

[英]scanf() without field width limits can crash with huge input data

所以基本上我想以這種方式輸入數據,例如“string:%d:%d:%d”,如果我使用“%s:%d:%d:%d”它不能停止掃描字符串,直到找到一個空格,但是如果我使用這個“ %[^:]:%d:%d:%d ”它可以工作,但是我使用 cppcheck 得到一個錯誤,它是:

scanf() without field width limits can crash with huge input data. Add a field width specifier to fix this problem.

Sample program that can crash:

#include <stdio.h>
int main()
{
    char c[5];
    scanf("%s", c);
    return 0;
}

Typing in 5 or more characters may make the program crash. The correct usage here is 'scanf("%4s", c);', as the maximum field width does not include the terminating null byte.

我不明白為什么,如果有人可以幫助我,我將不勝感激。

您可以使用

    int a, b, d;
    char c[5];
    if (scanf("%4[^:]:%d:%d:%d", c, &a, &b, &d) != 4)
    {
        exit(EXIT_FAILURE);
    }
//for your program example use scanf("%4s",c);

這是為了避免緩沖區溢出。

對於您的字符串,您可以掃描4字符(+1 為\0 ),否則您將通過數組的邊界,這將導致未定義的行為。

如果你想存儲更多數據,例如數組c中的面包,數組應該是char c[6]

這就是當您想要存儲數據並在scanf中添加這個數字時有足夠的空間,比如scanf("%5s",c); 將阻止scanf讀取超出我們空間的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM