Here are the steps for avoiding a buffer overflow using the fgets function:
- Define a structure consisting of two members, name and orderid.
- Define a variable of the structure type defined in step 1.
- Prompt the user to enter a value for the orderid member of the structure.
- Invoke the fpurge function to empty out the input stream buffer before invoking the fgets function.
- Invoke the fgets function to enter data for the name member of the structure. In order to constrain the size of the text to be assigned to name member, its length is computed by invoking the sizeof function and that length of string is supplied to the fgets function.
- Add a null character to the string, if one is not already there, to terminate the string.
- Display data assigned to the orderid and name members of the structure to verify that there is no buffer overflow.
The following program defines a structure consisting of two members and explains how a buffer overflow can be avoided while entering data through the keyboard:
//getssolved.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct users {
char name[10];
int orderid;
};
int main(void) {
struct users user1;
int n;
printf("Enter order number ");
scanf("%d", & user1.orderid);
fpurge(stdin);
printf("Enter user name ");
fgets(user1.name, sizeof(user1.name), stdin);
n = strlen(user1.name) - 1;
if (user1.name[n] == '\n')
user1.name[n] = '\0';
printf("Information of the user is - Name %s, Order number %d\n",
user1.name, user1.orderid);
}
Now, let's go behind the scenes to understand the code better.