user5401362
user5401362

Reputation:

Unpredictable string length when second argument of cin.getline() is greater than the length of array

using namespace std;
char str1[10],str2[10];
cin.getline(str1,14);
cin.getline(str2,10);
cout<<strlen(str1)<<'\t'<<strlen(str2);

The Output of the above code was as follows-

1234567890123
bye
13         3

How could be the length of str1 greater than 10?

Upvotes: 0

Views: 100

Answers (3)

Bathsheba
Bathsheba

Reputation: 234745

The behaviour of your overrunning a char array is undefined. To be clear, you need to ensure there is sufficient space for your data and a \0 string terminator else the behaviour of cout will be undefined.

The compiler is allowed to do anything if it encounters this.

Your output is a common manifestation, but you must not rely on such behaviour.

Upvotes: 3

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385224

It can't. You overran your buffer and overwrote memory outside of the array. Your program happened not to crash or teleport a cat into your monitor before it found a '\0' no earlier than 13 bytes in memory from the start of your 10-element array.

Upvotes: 4

marom
marom

Reputation: 5230

Because it is likely to use the space reserved for str2. But this is undefined behaviour, it could do anything (likely a segfault(access violation or whatever is named on your OS)

Upvotes: 0

Related Questions