Here are the steps to make a program in which an error occurs due to string formatting:
- Define a structure consisting of two members, name and orderid.
- Define a variable of the structure type defined in step 1.
- Assign any integer value to the orderid memberĀ of the structure.
- Invoke the sprintf function to assign formatted text to theĀ name member of the structure. In order to generate a buffer overflow, assign a larger text to it.
- Display data assigned to the orderid and name members of the structure to confirm if the ambiguous output is generated to verify whether buffer overflow has occurred.
The following is the program that generates an erroneous output because of applying string formatting:
//sprintfproblem.c
#include <stdio.h>
struct users {
char name[10];
int orderid;
};
int main(void) {
struct users user1;
user1.orderid = 101;
sprintf(user1.name, "%s", "bintuharwani");
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.