How it works...

The program will ask for two pairs of names and order numbers. In the first pair, we will deliberately generate a buffer overflow by entering text that is longer than the variable size, whereas for the second pair, we will enter the data within the specified range. Consequently, the information of the first user (pair) will be displayed incorrectly, that is, the data will not appear exactly the same as it was entered, whereas that of the second user will appear correctly.

So, we will define a structure called users with two fields or members called name and orderid, where name is defined as a string of size 10 bytes and orderid is defined as an int variable of 2 bytes. Then, we will define two variables user1 and user2 of the users structure type; that means both the user1 and user2 variables will get a name and orderid member each.

You will be prompted to enter the username and order number twice. The first pair of names and the order numbers entered will be assigned to user1 and the second to user2. The entered information of the two users is then displayed on the screen.

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

Figure 18.1

We can see in the preceding output that because of the buffer overflow made by the name member in the first structure, the value of the orderid member, which was 101, is overwritten. Consequently, we get a garbage value for the orderid of the first structure. The output of the second structure is correct because the value entered for its members is within their capacity.

To avoid overflow while entering data, we simply replace the gets function with the fgets function. With the fgets function, we can specify the maximum number of characters that can be allowed in the specified string. The extra text will be truncated and will not be assigned to the specified string.