簡體   English   中英

防止緩沖區溢出

[英]Preventing Buffer Overflow

我正在學習緩沖區溢出,並想知道防止用戶輸入的字符數超過允許的字符並導致緩沖區溢出的最佳方法是什么。

防止緩沖區溢出的最佳做法是什么?

這是我的代碼:

#include <iomanip>
#include <iostream>

int main()
{
    std::cout << "Buffer Overflow Example" << std::endl;

    // The user can type more than 20 characters and overflow the buffer, resulting in account_number being replaced -
    //  even though it is a constant and the compiler buffer overflow checks are on.
    //  I need to modify this method to prevent buffer overflow without changing the account_order
    //  varaible, and its position in the declaration. It must always be directly before the variable used for input.

    const std::string account_number = "CharlieBrown42";
    char user_input[20];
    std::cout << "Enter a value: ";
    std::cin >> user_input;

    std::cout << "You entered: " << user_input << std::endl;
    std::cout << "Account Number = " << account_number << std::endl;
}

防止輸入緩沖區溢出的最佳方法是使用不使用固定長度緩沖區的方法。 std::cin.getline() 是安全使用的一個很好的例子。

定義固定長度的 arrays 不是 C++ 做任何事情的方式。 如果你正在制作一個數組,你真的想考慮一下你是否使用了最好的方法。

暫無
暫無

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

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