0
#include<limits.h>
#include<errno.h>

long output;

errno = 0;
output = strtol(input,NULL,10);
printf("long max = %ld\n",LONG_MAX);
printf("input = %s\n",input);
printf("output = %ld\n",output);
printf("direct call = %ld\n",strtol(input,NULL,10));
if(errno || output >= INT_MAX || output <= INT_MIN) {
    printf("Input was out of range of int, INT_MIN = %d, INT_MAX = %d\n",INT_MIN,INT_MAX);
    printf("Please input an integer within the allowed range:\n");
}

上記のコードに {'1','2','3','4','5','6','7','8','9','0 の入力配列が与えられた場合','1'}

私は次の出力を取得します:

long max = 9223372036854775807
input = 12345678901
output = -539222987
direct call = 3755744309

何が起こっているのか... strtolはオーバーフローに苦しんでいるようですが、errnoを設定していません

4

1 に答える 1

6

<stdio.h>ほとんどの場合、必要なおよび/または<stdlib.h>ヘッダーが含まれていません。

それらを含めると、コードは正常に機能します(64ビットモードのGCC):

$ cat t.c
#include<limits.h>
#include<errno.h>
#include<stdlib.h>
#include<stdio.h>

int main (void)
{
    long output;
    char input[] = "12345678901";
    errno = 0;
    output = strtol(input,NULL,10);
    printf("long max = %ld\n",LONG_MAX);
    printf("input = %s\n",input);
    printf("output = %ld\n",output);
    printf("direct call = %ld\n",strtol(input,NULL,10));
    if(errno || output >= INT_MAX || output <= INT_MIN) {
        printf("Input was out of range of int, INT_MIN = %d, INT_MAX = %d\n",INT_MIN,INT_MAX);
        printf("Please input an integer within the allowed range:\n");
    }
    return 0;
}

$ gcc -Wall -Wextra -pedantic t.c
$ ./a.out
long max = 9223372036854775807
input = 12345678901
output = 12345678901
direct call = 12345678901
Input was out of range of int, INT_MIN = -2147483648, INT_MAX = 2147483647
Please input an integer within the allowed range:

ところで、呼び出しerrnoの直後に保存する必要がありstrtolます。呼び出したライブラリ関数strtolと条件によって値が変わる可能性があります。

于 2011-10-29T17:24:11.197 に答える