This is a typical buffer overflow. This is why you should always check the size of the input if you put it in the buffer. Here's what happens:
In C ++ (and C), array names are just pointers to the first element of the array. The compiler knows the size of the array and performs some compile-time checks. But at runtime, it will only be considered as char *.
When you did cin >> name1 , you passed char * to cin . cin does not know how significant the allocated space is - all it has is a pointer to some memory. Thus, it is assumed that you have been allocated enough space, everything is written and goes through the end of the array. Here is the image:
Bytes 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Before |-----name1 array-------| |--- other data-| After Q wertyuiop \0 |-er data-|
As you can see, you overwritten the other data that was saved after the array. Sometimes this other data is just garbage, but in other cases it is important and can mean a complex error. Not to mention that this is a security vulnerability, since an attacker could overwrite program memory using user input.
The confusion about sizes is that strlen will count bytes until it finds '\0' (the null terminator), which means it finds 10 characters. On the other hand, size(name1) uses the actual size of the array provided by the compiler.
Due to these problems, whenever you see a C function that takes an array as an argument, it also takes the size of the array. Otherwise, there is no way to say how great it is. To avoid these problems, it is much better to use C ++ objects such as std :: string.
source share