0

i am trying to set my own size to string array. how cin overwrite the size of string.

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
  int size; cin>>size;
  char str[size];
  cout << "Enter a string: ";
  cin>> str;
  cout << "string size: " << strlen(str);
  return 0;
}

output:

5
Enter a string: hellobaby
string size: 9
JaMiT
  • 14,422
  • 4
  • 15
  • 31
MD SAIF
  • 1
  • 2
  • `size` is the size you reserve for a string of length up to `size -1`. `size` might be 1024 while the length of `”test”` is 4 (plus one for ending null); the remaining 1019 characters are unused. Read about null-terminated strings. – zdf Feb 27 '21 at 10:34
  • That's something of an apples-to-oranges comparison. The size of the array holding a null-terminated string and the size of the null-terminated string are independent, unrelated quantities. *(Ideally the relation `string size < array size` holds, but it doesn't have to. That's a big reason why [`std::gets`](https://en.cppreference.com/w/cpp/io/c/gets) was removed in C++14.)* So `cin` does not really overwrite the size of anything. Perhaps you could rephrase the question to ask why `cin` is not limited by the size of the array? – JaMiT Feb 27 '21 at 11:50

1 Answers1

3

Here you create a VLA with size 5 (given the input in the question:

int size;
cin >> size;
char str[size];

You then go ahead and enter a string that is longer than that:

cin>> str; // hellobaby

That string is now written out of bounds so your program has undefined behavior. Anything can happen.

Instead of using non-standard VLA:s, you could use a std::string

#include <string>

unsigned size;
cin >> size;
std::string str;
cin >> str;
str.resize(std::min(str.size(), size));
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108