0

How do I use a c-string and avoid overflow? For example if I had the code:

#include <iostream>
using namespace std;

int main()
{
    int size = 1000;
    char * name = new char[size];
    getline(cin, name);
}

I don't know how long that persons name is going to be, so how do you avoid an overflow? If I allocated 1000 as a precaution, they could just as easily input 1001 characters. What can I do to stop this from happening?

edit: I have to be able to do this without the string class

3
  • 5
    Use std::string instead and make your life much simpler and your code easier to understand. Commented Feb 1, 2018 at 21:01
  • What do you think is the reason std::string was invented? Commented Feb 1, 2018 at 21:03
  • 5
    If you want to use a fixed buffer, use cin.getline(name, size) documentation here Commented Feb 1, 2018 at 21:04

1 Answer 1

5

There is a version of std::getline() which accepts std::string as target buffer. It is designed to take advantage of std::string's auto-resize capability and prevent overflows. Example from std::getline manpage:

#include <string>
#include <iostream>

int main()
{
    // greet the user
    std::string name;
    std::cout << "What is your name? ";
    std::getline(std::cin, name);
    std::cout << "Hello " << name << ", nice to meet you.\n";
}

In addition to the safety you asked about, std::string gives you also automatic memory management - so you don't need to remember to delete anything, which would be necessary in your example.


If you are not allowed to use std::string, you can use std::basic_istream::getline, which comes in two forms:

basic_istream& getline( char_type* s, std::streamsize count );
basic_istream& getline( char_type* s, std::streamsize count, char_type delim );

It allows you to specify max number of characters to read and an optional delimiter. std::basic_istream is the base class for std::istream. A very popular instance of this class is std::cin.

So basically, you can do:

char target[64];
std::cin.getline(target, 64);
Sign up to request clarification or add additional context in comments.

6 Comments

Sorry, I forgot to add that I can't use strings
You don't need to include sstream but otherwise +1 this is the exact answer.
@Dante then you're not using C++, you're using C.
@Tas I don't know how to use c like malloc so I said c++.
@Dante I updated my answer to also respect non-std::string-based approach.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.