1

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;
}
  • 6
    `std::cin.getline(user_input, 20);` ? ([getline](https://en.cppreference.com/w/cpp/io/basic_istream/getline)) – Borgleader Mar 13 '21 at 16:07
  • 4
    Because std::string avoids the buffer overflow problem and is better in every way. – drescherjm Mar 13 '21 at 16:13
  • 2
    There is also [https://en.cppreference.com/w/cpp/string/basic_string_view](https://en.cppreference.com/w/cpp/string/basic_string_view) – drescherjm Mar 13 '21 at 16:15
  • @drescherjm So in most cases, char should be avoided and strings should be used in their place? – BeardedArtist Mar 13 '21 at 16:16
  • 1
    c-strings in many cases should be avoided. – drescherjm Mar 13 '21 at 16:17
  • 2
    [https://stackoverflow.com/questions/10937767/when-to-use-stdstring-vs-char](https://stackoverflow.com/questions/10937767/when-to-use-stdstring-vs-char) – drescherjm Mar 13 '21 at 16:22
  • 1
    You could also use ```scanf("%19s",user_input);```, but some might frown upon that since its even more C code in an apparent C++ source file. – Armand Jordaan Mar 13 '21 at 16:29
  • 1
    sorta-dupe of [Are C++ strings and streams buffer overflow safe?](https://stackoverflow.com/questions/8015355/are-c-strings-and-streams-buffer-overflow-safe), and may be too broad on its own, although mostly very good advice so far – underscore_d Mar 13 '21 at 18:49

1 Answers1

3

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.

Joseph Larson
  • 8,530
  • 1
  • 19
  • 36