检查输入是否可能发生int溢出

时间:2019-02-19 16:40:54

标签: c

我已经阅读了一段时间,但是他们总是在进行操作时谈论溢出,但是在用户将其分配给int标识符之前,我如何真正检查潜在的int溢出? ?

我想在输入时检查输入内容,因此当发现该值已经超出int类型数据的值范围时,我可以在输入进行到代码的下一部分之前就停下来。

2 个答案:

答案 0 :(得分:7)

您可以读取一个字符串,然后使用 strtol 然后检查 endptr errno ,一切正常后,您可以分配您的 int var

详细使用 strtol

#include <stdlib.h>
#include <ctype.h>
#include <errno.h>

int main()
{
  char s[32]; /* 31 characters is surely large enough for an int */

  if (scanf("%31s", s) != 1)
    puts("nok");
  else {
    errno = 0;

    char * endptr;
    long int l = strtol(s, &endptr, 10);

    if (endptr == s)
      puts("no digit");
    else if ((*endptr != 0) && !isspace(*endptr))
      puts("invalid number");
    else if (errno != 0)
      puts("overflow on long");
    else if (((int) l) != l) /* in case long and int do not have the same size */
      puts("overflow on int");
    else
      puts("you enter a valid int");
  }

  return 0;
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra s.c
pi@raspberrypi:/tmp $ ./a.out
a 
no digit
pi@raspberrypi:/tmp $ ./a.out
12z
invalid number
pi@raspberrypi:/tmp $ ./a.out
123
you enter a valid int
pi@raspberrypi:/tmp $ ./a.out
12345678901
overflow on long

所以要准确回答这个问题:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>

int readInt(int * v)
{
  char s[32]; /* 31 characters is surely large enough for an int */

  if (scanf("%31s", s) != 1)
    return 0;
  else {
    errno = 0;

    char * endptr;
    long int l = strtol(s, &endptr, 10);

    if ((endptr == s) ||       /* no digit */
        ((*endptr != 0) && !isspace(*endptr)) || /* e.g. 12a */
        (errno != 0) ||        /* overflow on long */
        (((int) l) != l))      /* overflow on int */
      return 0;

    *v = (int) l;
    return 1;
  }
}


int main()
{
  int v = 123;

  if (readInt(&v))
    printf("new valid in value : %d\n", v);
  else
    printf("unvalid input, still %d\n", v);

  return 0;
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra s.c
pi@raspberrypi:/tmp $ ./a.out
12
new valid in value : 12
pi@raspberrypi:/tmp $ ./a.out
9878787878787878
unvalid input, still 123
pi@raspberrypi:/tmp $ 

答案 1 :(得分:1)

如果必须直接读入int,则在分配之前不能真正检查溢出。

如果不是直接读入int的要求,则有很多方法可以解决。例如,您可以读取一个字符缓冲区/字符串,然后检查输入是否为数字以及输入是否适合int。如果是这样,则可以使用标准库函数将字符缓冲区转换为整数,然后分配给您的int。