How it works...

We want to enter information about the customer's name and the order placed by them. So, we define a structure called users with two members, name and orderid, where the name member is defined as a character array of length 10 bytes, and the orderid member is defined of the int data type consisting of 2 bytes. A variable, user1, is defined of the users structure type, hence the user1 structure will get two members, name and orderid. An integer of value 101 is assigned to the orderid member of the user1 structure.

Using the sprintf function, a string, bintuharwani, is assigned to the name member of the user1 structure. The bintuharwani string is larger than the name member, hence a buffer overflow will occur, overwriting the memory of the next memory location, that is, the memory of the orderid member. So, while displaying the information of the user, the name will appear correctly but you will get a different or ambiguous value for the orderid member.

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

Figure 18.5

In the output, you can see that the order number is displayed incorrectly; that is, instead of the assigned value, 101, it displays the value 0. This is because on assigning the bintuharwani string to the name member, the fact that the string is larger in size than the capacity of the name member leads to a buffer overflow that overwrites the value of the orderid member.