In this recipe, everything is the same as the previous recipe. The point of difference is that we invoke the strncpy function. When this function is invoked, only the strsize number of bytes from the administrator text is assigned to the name member of the user1 structure. Because strsize contains the maximum length of the name member, no buffer overflow will occur in this case.
Finally, we check if the null character, \0, exists as the last character in the name member. If not, then the null character is added at its end to terminate the string. On displaying the information of the user, we see that because the length of the name member is 10, only the first 9 characters from the text administrator are assigned to the name member, followed by a null character. As a result of this, the value of the orderid member will also appear correctly, exactly the same as was entered.
Let's use GCC to compile the strcpysolved.c program. If you get no errors or warnings, it means the strcpysolved.c program has compiled into an executable file: strcpysolved.exe. Let's run this file:
You can see in the preceding output that whatever value is entered for the two members, we get exactly the same output.