防止缓冲区溢出

问题描述

我正在了解缓冲区溢出并想知道什么是防止用户输入超过允许的字符数并导致缓冲区溢出的最佳方法。

防止缓冲区溢出的最佳做法是什么?

这是我的代码:

#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;
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)