I have a code
char s[5];
cin >> s;
cout << strlen(s);
cout << endl;
cout << s;
It works even if I input more than 5 chars, for example "qwertyui". Does it mean that I am using not allocated memory?
I have a code
char s[5];
cin >> s;
cout << strlen(s);
cout << endl;
cout << s;
It works even if I input more than 5 chars, for example "qwertyui". Does it mean that I am using not allocated memory?
strlen(s)
is something, but has nothing to do with 5
. strlen
applies to C strings, which are char arrays, but their length is defined as the numbers of characters until the first zero byte happens.
Now, cin
in your second line cannot know how long your char[]
is, so it just accepts as much input as there is. You must never use char buffers for input you don't know is well-formed. What you're seeing is a buffer overflow in action. Writing over memory that doesn't belong to any variable you allocated results in undefined behaviour, so your program might just work, crash with e.g. a segfault (accessing memory that the OS never gave you), or overwriting existing part's of your processes' memory, or … just do anything, because it's really undefined.
So, you're writing C++, not C. just
string s;
cin >> s;
cout << s.length()
<< endl
<< s;
to avoid dealing with the (very dangerous) C strings.
You're right, it might still echo correctly if you write more than 5 characters. You're simply writing off the end of the buffer, and just blasting the memory that's next to the memory allocated for char s[5]
. This is bad for many reasons, including security vulnerabilities. See here for details.
If you can't use string
(for whatever reason), use fgets
. See here for the documentation on fgets
and how it is used. NEVER USE gets
. It's almost equivalent to what you've done above, see here for why gets is so dangerous.