简体   繁体   English

防止缓冲区溢出

[英]Preventing Buffer Overflow

I am learning about buffer overflows and want to know what is the best way to prevent a user from entering more characters than is allowed and causing a buffer overflow.我正在学习缓冲区溢出,并想知道防止用户输入的字符数超过允许的字符并导致缓冲区溢出的最佳方法是什么。

What are the best practices to prevent buffer overflows?防止缓冲区溢出的最佳做法是什么?

Here is my code:这是我的代码:

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

The best way to prevent buffer overflow on input is to use methods that don't use fixed-length buffers.防止输入缓冲区溢出的最佳方法是使用不使用固定长度缓冲区的方法。 std::cin.getline() is a good example of something that is safe to use. std::cin.getline() 是安全使用的一个很好的例子。

Defining fixed-length arrays is so NOT the C++ way to do anything.定义固定长度的 arrays 不是 C++ 做任何事情的方式。 If you're making an array, you really want to think about whether you're using the best method.如果你正在制作一个数组,你真的想考虑一下你是否使用了最好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM