简体   繁体   中英

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.

Defining fixed-length arrays is so NOT the C++ way to do anything. If you're making an array, you really want to think about whether you're using the best method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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