How to do it...

Here are the steps to make a program that will lead to a buffer overflow:

  1. Define a structure consisting of two members, name and orderid.
  2. Define two variables of the structure type defined in step 1. In one of the structure variables, we will deliberately generate a buffer overflow by entering a large amount of data.
  3. Prompt the user to enter a value for the orderid member for the first structure.
  4. Invoke the fpurge function to empty out the input stream buffer before invoking the gets function.
  5. Invoke the gets function to enter data for the name member for the first structure. Enter text that is larger than the length of the name member.
  6. Repeat steps 3 to 5 to enter data for the orderid and name members for the second structure. This time, enter data within the capacity of the name member.
  7. Display data assigned to the orderid and name members of the first structure. Buffer overflow will occur in the case of the first structure and you will get an ambiguous output while displaying the orderid value.
  8. Display data assigned to the orderid and name member of the second structure. No buffer overflow takes place in this structure and you get exactly the same data that was entered for both the members.

The following program will take the name and order number values for two structures. In one member of the structure, we will enter data that is larger than its capacity to generate a buffer overflow:

//getsproblem.c

#include <stdio.h>

struct users {
char name[10];
int orderid;
};
int main(void) {
struct users user1, user2;
printf("Enter order number ");
scanf("%d", & user1.orderid);
fpurge(stdin);
printf("Enter first user name ");
gets(user1.name);
printf("Enter order number ");
scanf("%d", & user2.orderid);
fpurge(stdin);
printf("Enter second user name ");
gets(user2.name);
printf("Information of first user - Name %s, Order number %d\n",
user1.name, user1.orderid);
printf("Information of second user - Name %s, Order number %d\n",
user2.name, user2.orderid);
}

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