2

I know,that in char[], in between square brackets we write the lenght of character.

For example, if we write char[10], it should give us 10 characters or less.

But, in my code, where I input my name "Ramunas"(which is 7 characters), instead of giving me 5 characters(Ramun), it still ends up giving "Ramunas". Why does that happen?

#include <iostream>
using namespace std;
int main()
{
    char a[5];
    cout<<"Hello, enter your name: "<<endl;
    cin>>a;
    cout<<a<<endl;
    return 0;
}
  • 4
    It is because the program has undefined behavior. You overwrote the memory beyond the array. – Vlad from Moscow Apr 16 '20 at 10:57
  • 2
    Note that "Ramunas" is 8 characters when you count the null terminator character. Also note that "Ramūnas" is potentially even more chars in unicode encoding. – eerorika Apr 16 '20 at 11:02
  • 1
    Here is an example. Everything seems correct but you overwrote the variable `i`: https://wandbox.org/permlink/p2LpOvIrVat3laaa – Thomas Sablik Apr 16 '20 at 11:07

1 Answers1

6

This is called a buffer overflow. cin only knows the address of the array and does not check the size of allocated (or not) memory behind this address.

cout also does not perform any check here. It starts reading chars at the provided address until it finds '\0'.

You can prevent buffer overflow in this case by explicitly limiting the number of chars that cin accepts.

cin >> std::setw(5) >> a
log0
  • 10,489
  • 4
  • 28
  • 62