Others have pointed out that it is undefined behaviour. What this means is that when you have char a[4]
and you attempt to access anything that is out-of-bounds (e.g. a[4] = 't'
), then there is no guarantee as to how your program behaves. In some cases, it may work, and in other cases, it may crash. Since there is no guarantee, it is particularly useless to depend on such code.
The problem with gets()
is that you can't tell it how big the buffer is, so it has no idea when to stop writing to the supplied buffer. You entered in 11 characters, and gets
has performed the equivalent of:
a[0] = 'm';
a[1] = 'e';
a[2] = 'l';
a[3] = 'w';
a[4] = 'i'; // at this point, we are writing out-of-bounds
a[5] = 'n';
/* ... etc ... */
a[12] = '\0';
In C, there are no automatic bounds checks, and there are simply no guarantees as to what will happen.
Functions that write to a buffer that cannot be limited are generally considered unsafe (unless the function is documented not to write more than a certain number of characters, etc.).