如何防止我的代码出现以下的转换错误?

huangapple go评论49阅读模式
英文:

How to prevent my code from the following conversion error?

问题

这可能听起来像一个XY问题,但我感到困惑。

我想在用户输入6时执行一些代码。首先看一下代码:

#include <stdio.h>

int main(void) {

     short int x;
     printf("Val :");
     scanf("%d", &x);
     if (x == 6) {
          //一些代码
     }

     return 0;
}

在我的系统中,SHRT_MAX的值是32767,如果用户设法输入65442,它最终会被转换为6,然后在这个值上执行代码,尽管本应在6上执行。嗯,它确实在6上执行,但从用户的角度来看,这并不安全。是的,我可以使用intlong int,但如果用户破解short int,这并不是正确的选择。我该如何处理这个问题?

英文:

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&lt;stdio.h&gt;

int main(void) {

     short int x;
     printf(&quot;Val :&quot;);
     scanf(&quot;%d&quot;, &amp;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

得分: 7

> Re: SHRT_MAX in my system is 32767 and if user manages to enter 65442 this will be converted to 6
关于我的系统中的SHRT_MAX为32767,如果用户设法输入65442,则会转换为6。

From C11 7.21.6.2 The fscanf() function /10:
来自C11 7.21.6.2中的fscanf()函数/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.
我建议读取整行使用fgets(),然后用strtol()进行解析。scanf()不适合此情况。

This might help: Correct usage of strtol().
这可能有所帮助:正确使用strtol()

Sidenote: The %d format specifier expects an int *, not a short int *. Change it to %hd.
附注:%d格式说明符预期是一个int *,而不是一个short int *。将其更改为%hd

英文:

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

huangapple
  • 本文由 发表于 2023年5月28日 21:17:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76351703.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定