How to do it...

Here are the steps to understand how a vulnerability occurs 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.
  1. Invoke the strcpy function to assign text to the name member of the structure. In order to generate a buffer overflow, assign a larger text to it. 
  2. Display data assigned to the orderid and name members of the structure to confirm if the ambiguous output is generated, which verifies that a buffer overflow has occurred.

The program that shows a vulnerability when copying a string is as follows:

//strcpyproblem.c

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

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

int main(void) {
struct users user1;
char userid[] = "administrator";
user1.orderid = 101;
strcpy(user1.name, userid);
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.