0

I'm reviewing the basics of C++ to understand the fundamentals. I wonder why my C++ program prints out the complete string when I input the longer string into the character array which is defined as shorter than the input string.

#include <iostream>

int main()
{
    using namespace std;
    const int Size = 2;
    char carr[Size];

    cin >> carr;
    cout << carr << endl;
}

When I input "abcde" to the program, I outputs the whole string "abcde" even though the character array carr's length is only 2.

How does this work?

Han
  • 625
  • 2
  • 7
  • 25

1 Answers1

0

When you input a "long" string into a "short" char[], you're writing to memory you haven't allocated. This has undefined behavior in C[++], and also it may work in certain situations, it may very well also crash with a segmentation fault.

Mureinik
  • 297,002
  • 52
  • 306
  • 350