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. ...