In: Computer Science
How would you correct this function in C to prevent buffer overflow using the fgets() function and strncat() function
void nameBuilder()
{
char fname[10];
char lname[10];
char fullname[20];
printf("Enter your first name: ");
scanf("%s", fname);
printf("Enter your last name: ");
scanf("%s", lname);
strcat(fullname, fname);
strcat(fullname, " ");
strcat(fullname, lname);
printf("Welcome. %s\n", fullname);
return;
}
As seen from the program, the array size of fname and lname is 10 which means that it can contain maximum of 10 characters including the null character.
But, scanf function does not put any restriction on the input size. Let’s say if someone gives an fname or lname of length >=9, it will result in a buffer overflow.
Using fgets, the maximum size of input can be specified which prevents the buffer overflow.
strcat produces a string which is a null-terminated string whereas strncat produces a string which is either terminated at the length specified or by a null termination whichever is shorter in length.
Code:
void nameBuilder()
{
char fname[10];
char lname[10];
char fullname[20];
printf("Enter your first name: ");
// specify 10 as size because max size of fname can be 10
fgets(fname, 10, stdin);
printf("Enter your last name: ");
// specify 10 as size because max size of lname can be 10
fgets(lname, 10, stdin);
// specify 10 as size because max size of fname can be 10 which will be appended to fullname
strncat(fullname, fname, 10);
// specify 1 as size because size of “ “ can be 1 which will be appended to fullname
strncat(fullname, " ", 1);
// specify 10 as size because max size of lname can be 10 which will be appended to fullname
strncat(fullname, lname, 10);
printf("Welcome. %s\n", fullname);
return;
}
Output:
Enter your first name: Nelson
Enter your last name: Mandela
Welcome. Nelson Mandela