How it works...

In the program, the fgets function takes input from the standard input device and the maximum number of characters that will be read from the input device will be equal to the number of bytes allowed in the name variable of the user1 structure. As a result, even if the user enters a larger string, only the specified number of bytes from the input will be picked up; that is, only the first 10 characters in the input will be picked up and assigned to the name member of the user1 structure.

The fgets function appends the null character (\0) to the string, provided the number of characters entered is one less than the maximum length specified in the function. But for the string that is larger than the specified length, we need to insert the null character at the end of the string. To do so, we need to check if the newline character is there as the last character of the string. If yes, then we replace the newline character in the string with the null character to terminate the string.

Let's use GCC to compile the getssolved.c program. If you get no errors or warnings, it means the getssolved.c program has compiled into an executable file: getssolved.exe. Let's run this file:

Figure 18.2

We can see in the preceding output that the larger text assigned to the name member of the structure is truncated as per the member's size, hence no buffer overflow occurs.