How to do it...

Here are the steps to make secure code while copying a string:

  1. Define a structure consisting of two members, name and orderid.
  2. Define a variable of the structure type defined in step 1.
  3. Assign any integer value to the orderid member of the structure.
  4. Determine the length of the name member of the structure to find the maximum number of characters that it can accommodate.
  5. Invoke the strncpy function for copying a text to the name member of the structure. Pass the length of the name member, too, to the strncpy function to truncate the text if it is larger than the capacity of the name member.
  6. Add a null character to the string, if it is not there already, to terminate it.
  7. Display data assigned to the orderid and name members of the structure to verify that a buffer overflow does not occur and the same data is displayed as was entered.

The program that is secure enough for copying strings is as follows:

//strcpysolved.c

#include <stdio.h>
#include <string.h>

struct users {
char name[10];
int orderid;
};

int main(void) {
int strsize;
struct users user1;
char userid[] = "administrator";
user1.orderid = 101;
strsize = sizeof(user1.name);
strncpy(user1.name, userid, strsize);
if (user1.name[strsize - 1] != '\0')
user1.name[strsize - 1] = '\0';
printf("Information of the user - Name %s, Order number %d\n",
user1.name, user1.orderid);
}

Now, let's go behind the scenes to understand the code better.