Hello everyone. I was writing somthing in C++ today and a little "issue" occured to me. How can you avoid the possibility of a buffer overrun when reading from STDIN into a character array? In this simple example

#include <iostream>
using namespace std;

int main ()
{
char *some_text = new char[10];
cout <<"Enter some sample text: ";
cin >> *some_text;
}

all seems well and good at first glance. But if someone enters more than 9 characters at the prompt they'll be a buffer overrun. The string of characters entered by the user is (I assume) copied into *some_text from a buffer outside the program. So how do you make sure no more than 10 characters are copied into *some_text? Begginers question I know, but an important one. Any answers appriciated.

Steven.

Recommended Answers

All 6 Replies

you can use getline()

cin.getline(some_text, 10);

>>cin >> *some_text;
incorrect syntax. remove the asterisk (star).

Thanks you two. Problem solved. I like the avatar Salam and a nice sentiment, keeping to standards and all that. But tell me, can using

void main ()

ever cause undefined behavior in a program?

Steven.

C and C++ standards dictate that main() must return an integer. Some compilers produce error message for this, while other older compilers do not. main() will return an integer whether you declare it int or something else such as void.

But tell me, can using

void main ()

ever cause undefined behavior in a program?

Ever? Yes. See this

Under normal circumstances, though, no. But since it's wrong, don't use void.

> ever cause undefined behavior in a program?
You should be writing your programs to be correct, not to what you think you can get away with.

From a practical point of view, I once had to deal with a pretty useful batch program written by a void main'er. Rather than returning predictable 0, 1, 2 depending on the exit status of the program, it just fell off the end and the exit status was 22, 78, 46 or other random chaos. I really wanted to give that programmer a damn good smack with the clue bat.

Even if you've no intention of porting this program to another OS / Compiler, there is something which will eventually have to deal with another OS / Compiler, and that is YOU.

It's all very well learning a bunch of mush, but it sure is hell when you move to another platform and all your old tricks and assumptions no longer work. If you thought learning C was hard, try unlearning bad C.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.