0

When I declare a char array of length 2 and then input a string of length greater than 2, it doesn't give an error and outputs the whole string. Does that mean extra size is allocated dynamically?

Sample code:

char arr[2];
cin >> arr;
cout << arr << endl;

Input = "Hey"
Output = "Hey"

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 3
    No, it means [that a bunch of demons just flew out of your nose](http://www.catb.org/jargon/html/N/nasal-demons.html) but you haven't noticed it yet. – Sam Varshavchik Jan 02 '23 at 17:58
  • 4
    And still it is wrong. You access the array out of its boundaries and thats illegal (lookup : undefined behavior). C++ doesn't babysit, the fact that a program compiles doesn't mean it is correct. Anyway with C++ you should use [std::string](https://www.learncpp.com/cpp-tutorial/introduction-to-stdstring/) for dynamically allocated strings. – Pepijn Kramer Jan 02 '23 at 17:59
  • Your code has [undefined behaviour](https://en.cppreference.com/w/cpp/language/ub) and there's no guarantee about what it will do. – Jesper Juhl Jan 03 '23 at 00:44
  • [Undefined, unspecified and implementation-defined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior) – Jesper Juhl Jan 03 '23 at 00:44

0 Answers0