Why is this a buffer overflow?

Started by
4 comments, last by Zahlman 17 years, 2 months ago
Why is this a buffer overflow and why is it not proper to use?
char name[number]; 

cin >> name; 

//or

std::cin >> name;. 

//would this be correct?
getline(cin, name);

THanks Chad
Advertisement
That's an easy one. Let's say that number is 20. so you're code is effectively:
std::cout << "Enter your name: ";char name[20];std::cin >> name;


So I run the code and see this and type my name:

Enter your name: AbracadabracusTheGreatestOfAllTime

That's way over 20 characters(36 including the null character). What this will do is overwrite Something. We can't be sure what exactly. Probably code for the program. What this means is a malicious person could enter in something that changes the behavior of the program.

The correct way is to use std::string which will always be large enough for any string the user enters. Like so:
#include <iostream>#include <string>int main(){  std::cout << "Enter your name: ";  std::string name;  std::getline(std::cin, name);  std::cout << "Your name is " << name;  return 0;}

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

Because the user might type more than "number" letters.

Your second example can also be a buffer overflow, assuming name is a char array.

The way to avoid the possiblity of a buffer overflow is to use a std::string instead of a char array:

#include <string>#include <iostream>std::string name;void f(){    std::getline(std::cin,name); // this will read up to the first "return" character    // or    std::cin >> name; // this will only read up to the first whitespace   }


HTH
Quote:Original post by chadsxe
Why is this a buffer overflow and why is it not proper to use it.

Well, what happens if I type in number + 1 characters?

Your char array has no bounds checking, so I can enter as much data as I like, even though there's only allocated enough space for 'number' characters.

So the correct way is to not use a char array (or char*) for strings.

Do something like this instead:

std::string name;std::cin >> name;


std::string makes sure there's actually room for the chars you're trying to store into it.
Awesome...that makes perfect sense.

Thank everyone

CHad
Reading into a std::string via the >> operator will read one "word" of text (separated by whitespace such as spaces, tabs or newlines). To read a line, use the *free* function std::getline(), which accepts a std::istream& and a std::string&. The *member* function .getline() of istreams reads "into" char*s, which again opens the possibility of buffer overflows.

This topic is closed to new replies.

Advertisement