簡體   English   中英

C提示被覆蓋

[英]C prompt being overwritten

我是C語言的新手,我遇到了一個奇怪的問題。

這段代碼是一個更大程序的一部分,但是問題在這里,但我似乎無法弄清楚。

#include <stdio.h>
#include <string.h>
#define WORDSIZE 512

int read_stdNum(const char prompt[], char store[], size_t n) {
    char inHold[WORDSIZE];
    char process[10];
    int status = 0;

    while (1) {
        fprintf(stderr, "%s", prompt);

        if(fgets(inHold, WORDSIZE, stdin) == NULL) {
            return 0;
        }

        sscanf(inHold, "%s", process);

        status = sscanf(process, "%s", store);

        if (status > 0 && strlen(store) == n) {
            return 1;
        } else if (status == -1) {
            continue;
        } else {
            continue;
        }
    }
}

int main(void) {
    char arrow[] = "\n==> ";
    char stdNum[10];

    printf("%s\n", "store_student called.");

    fprintf(stderr, "%s", "\nEnter a student number (axxxxxxxx)\n");
    read_stdNum(arrow, stdNum, 9);
    return 0;
}

該程序要求用戶輸入,此處的測試是該程序截斷多余的數字,但是當我鍵入類似“ a123456789101112131415 ”的內容時,輸出為空,效果很好,但是提示被覆蓋並且提示看起來像這樣:

==> a123456789101112131415
131415_

下划線是我仍然可以輸入的地方。 字符數組“ process”也存儲了9個以上的字符。 我問了我的一些同學,其中一個說在他的電腦上工作正常。 我知道我會因為愚蠢而被炒魷魚,但我真的很想知道為什么這不起作用。 謝謝。

具有“ %s ”的scanf函數可能不安全,並且會導致緩沖區溢出(它可能會在輸出字符串中寫入比分配給該字符串的空間更多的字節,從而覆蓋一些有用的數據),請檢查https://cwe.mitre.org/data/ definitions / 120.html “ CWE-120:不檢查輸入大小的緩沖區復制('經典緩沖區溢出')”和示例1

https://zh.wikipedia.org/wiki/Scanf_format_string#漏洞

這意味着使用不帶長度說明符的%s占位符本質上是不安全的,可用於緩沖區溢出。

scanf文檔對使用s格式有一些要求(數組必須足夠長) http://man7.org/linux/man-pages/man3/scanf.3.html

  s Matches a sequence of non-white-space characters; the next pointer must be a pointer to the initial element of a character array that is long enough to hold the input sequence and the terminating null byte ('\\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first. 

類似scanf的函數的更安全用法是使用%9sm類的“最大字段寬度”進行動態內存分配。

(您對strlen檢查為時已晚; sscanf已經對字符串進行了溢出/覆蓋,因為它對讀取的長度沒有限制。)

暫無
暫無

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

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