#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
char first_name[20];
char last_name[20];
int student_num;
char debts[1];
printf("Enter name:");
scanf("%s", first_name);
printf("Enter lastname:");
scanf("%s", last_name);
printf("Enter six bits length student ID:");
scanf("%d", &student_num);
printf("Do you have debts for university [Y/N]?");
scanf("%s", debts);
printf("\nYour name is %s %s.\n", first_name, last_name);
printf("Your Student ID is %d.\n", student_num);
printf("Debts: %s.\n", debts);
return (EXIT_SUCCESS);
}
How to avoid buffer overflow in this code? I want my code to produce such an output:
Enter name:Enescekilokoneyasharrontannamyantoniaaquin
Enter lastname:Basenau
Enter six bits length student ID:456789
Do you have debts for university [Y/N]?YES
Your name is **Enescekilokoneyashar** (only 20 bits from name input) *Basenau*.
Your Student ID is **393299**.
Debts: **Y**.
Process returned -1073741819 (0xC0000005) execution time : 36.336 s
Press any key to continue.
I have tried to use:
scanf("%19s", first_name);
But it does not work as I expect. I need to find some another way to validate input parameters to prevent buffer overflow attack and limit input to buffers size.
scanf()is a horrible function to parse input, as you're finding out. When it fails to convert input, it leaves your input stream in an unknown state, which is really bad if it's a stream likestdinwhere you can't go back. Even more perverse, if you write a set of fields using a format string with[f]printf(), that same format string isn't guaranteed to be able to read that same data when used byscanf(). It's usually much better to read an entire line viafgets()(orgetline()if available) and parse the string yourself. You can even usesscanf()to replicatescanf().scanf()'s "Did I leave the newline in the buffer or not?!?" uncertainty whenscanf()is mixed with other input-reading functions.