It may sound like an XY Problem but I am confused.
I want to execute some code when the user enters 6. First have a look at code:
#include<stdio.h>
int main(void) {
short int x;
printf("Val :");
scanf("%d", &x);
if (x == 6) {
//some code
}
return 0;
}
SHRT_MAX in my system is 32767 and if the user manages to enter 65442 this will be converted to 6 ultimately and the code will be executed at this value while it was supposed to execute at 6. Well, it is getting executed at 6 but from the user's point of view it is the lack of security. Yeah, I can use int or long int, but if the user is cracking short int, it is not the right choice. How can I deal with this issue?
1 Answer 1
Re: SHRT_MAX in my system is 32767 and if user manages to enter 65442 this will be converted to 6
From C11 7.21.6.2 The fscanf() function /10:
If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.
I suggest reading a whole line fgets() and parsing it with strtol(). scanf() is not suitable for this.
This might help: Correct usage of strtol().
Sidenote: The %d format specifier expects an int *, not a short int *. Change it to %hd.
2 Comments
long using parsing function it may react the same way for overflow numbers. So should I use string comparing method to get the job done or some idea with numerical data ? i mean using premitive data types of number values ?
short intwithscanf, you need%hd.scanf. Regardless of whether the target type isshort,int,long, orlong long, if the user types a too-big value, there's no guaranteed behavior. (In fact I'm pretty sure it's downright undefined.)*scanf()functions to parse numeric data. There's no way to to use any of those functions without risking undefined behavior on an out-of-range value.*scanf()functions. What happens when your just-out-of-college self-styled "l33t" coder gets the ticket to change that format, and three weeks after delivery to production, one of your biggest customers calls up all irate because he just had a livestock trailer unleash 100 full-grown pigs onto his factory floor and his account was directly debited for rush delivery of said pigs and you find out your ordering system messed up a rush order for 100 tons of pig iron because your noob screwed up thescanf()format?scanf()and How to read/parse input in C — The FAQ.