Here is an easy question. I wrote this C++ code:
char chaine[12];
cin.width(12);
cin >> chaine;
But if I enter some text longuer than 12 characters at runtime, visual studio inform me that the stack is now corrupted.
I understand that the problem is a buffer overflow. But I thought that the “width” method would protect against this.
Could someone explain to me what is the function of the width method if it does not protect against the buffer overflow? I searched online but i did not find anything.
Thanks!
This code is indeed clearly supposed to limit the input to 11 characters (the 12th character is used for the terminating null character). The standard clearly states in 27.7.2.2.3 [istream::extractors] paragraphs 7 and 8:
I also tried it with gcc which clearly only reads 11 characters. I don’t know what the best work-around for this problem is. Typically, I don’t run into problems like this because I simple read
std::stringobjects which can grow as big as they want. Well, there is some huge limit as well and I have never tried what happens when this would get exceeded. If you absolutely need to read into achararray you could do two things:chararrays and define a suitable input operator yourselfBelow is an example on how to do the latter. The technique for creating the adapter can actually be used to set the width automatically based on the array’s size.