Skip to main content
GameDev.net gamedev.net
🔒 Locked

Why is this a buffer overflow?

Started by chadsxe Jan 25, 2007 at 10:24 AM 4 replies 650+ views
Original Post
chadsxe
chadsxe
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
nobodynews
nobodynews
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) ,
Aardvajk
Aardvajk
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
Spoonbender
Spoonbender
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.
chadsxe
chadsxe
Awesome...that makes perfect sense.

Thank everyone

CHad
Zahlman
Zahlman
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.