0
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?

3 Answers3

4

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
3

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Then why there was not any runtime error related to segmentation fault? My compiler is g++4.8.2 running on gnome terminal of Ubuntu 14 –  Jan 08 '16 at 11:37
  • 1
    Because your compiler was kind to you. It could have eaten your cat. That's the nature of undefined behaviour. C++ doesn't make what it considers to be unnecessary runtime checks. – Bathsheba Jan 08 '16 at 11:37
  • 1
    @dlpcoder: Segmentation faults are not guaranteed every time you overrun a buffer (generally only when you overrun it so much that you're requesting from the OS memory that's on an inaccessible virtual memory page, or dereferencing a null pointer). Many (most?) security exploits rely on this fact. – Lightness Races in Orbit Jan 08 '16 at 11:47
0

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)

marom
  • 5,064
  • 10
  • 14