Dear C++ users,
I am currently learning C++ and need some precision about the cin/cout extract/insert operators and buffer overflow.
Here is a small program to illustrate my questions (I know the code below is not
good programming style):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include <iostream>
int main()
{
using namespace std;
char str[5] // C_Style string to hold 5 char including null.
cout << "Please enter a string: ";
cin >> str;
cout << "You have entered: " << str;
return 0;
}
|
Question 1:
My understanding is that if I enter
abcdefg when prompted, I will provoke a buffer overflow and write over the array's boundary.
In the event that the program doesn't crash (as it happened on my computer), the output produced by cout gives
abcdefg.
Shouldn't it be just
abcde or only the 5 characters the array can hold?
Why do I get all the characters entered and not what can be hold by the array (only 5 characters)? (is it because of the absence of the null at the end?)
Question 2:
Could you please confirm my understanding below?
If I apply the extract (>>) operator on cin and the destination is a char array, all the characters found before the first
blank will be sent to the array
without checking boundaries. This is because the array is represented by a pointer and that pointer has no information about the size of the array.
Am I right?
Many, many thanks in advance for your patience, time and explanation!
kind regards