strtoul 给出意外的输出

strtoul giving unexpected output

我正在尝试使用 strtoul 函数,但如下所示 return 产生了一个意外值(在开头添加了 ff):

#include <stdio.h>
#include <string.h>
#include <limits.h>

main() {
    unsigned long temp ;
    char *err;
    temp = strtoul("3334444444",&err,10);
    if (temp > UINT_MAX) {
        printf("%lx %x %x\n",temp,3334444444,UINT_MAX);
    }else 
        printf("%lx %x\n",temp,3334444444);
}

$./a.out
ffffffffc6bf959c c6bf959c ffffffff 

上面的输出对应于 if 部分为真,尽管我希望 else 部分在这里得到执行。任何人都可以解释为什么 strtoul 会这样吗?为什么它是 return ffffffffc6bf959c 而不是 c6bf959c?如果我在上面的代码中使用 "333444444"(即少一个 4)而不是 "3334444444",那么我将得到对应于 else 部分的正确输出(即 13dff55c 13dff55c) .

Note : As pointed by melpomene in his reply below, stdlib.h header file should have been included and that will resolve the issue. Can anyone please let me know what is being done by the program by assuming the incorrect return type (int in this case) during compile time which can't be undone (or atleast it is not getting undone in this case) even after knowing the correct return type (unsigned long in this case) during link time ? In short, i want to know how c6bf959c is getting converted to ffffffffc6bf959c because of prototype not provided.

在启用警告的情况下使用 gcc 编译代码给出:

try.c:5:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
 main() {
 ^~~~
try.c:5:1: warning: function declaration isn’t a prototype [-Wstrict-prototypes]
try.c: In function ‘main’:
try.c:8:12: warning: implicit declaration of function ‘strtoul’ [-Wimplicit-function-declaration]
     temp = strtoul("3334444444",&err,10);
            ^~~~~~~
try.c:8:5: warning: nested extern declaration of ‘strtoul’ [-Wnested-externs]
     temp = strtoul("3334444444",&err,10);
     ^~~~
try.c:10:22: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 3 has type ‘long long int’ [-Wformat=]
         printf("%lx %x %x\n",temp,3334444444,UINT_MAX);
                      ^
try.c:12:22: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 3 has type ‘long long int’ [-Wformat=]
         printf("%lx %x\n",temp,3334444444);
                      ^

主要问题是implicit declaration of function ‘strtoul’,表明函数未声明(因此假定为return int),因为您忘记了#include <stdlib.h>。添加缺失的 #include 可修复 temp.

的值

但是您还应该查看针对 printf 报告的警告并修复它们。