strtoul给出意想不到的输出

时间:2016-07-18 19:41:44

标签: c strtol

我正在尝试使用strtoul函数,但如下所示,它返回了一个意外的值(在开头添加了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表现得像这样?为什么它会返回ffffffffc6bf959c而不仅仅是c6bf959c?如果我在上面的代码中使用"333444444"(即只减少了4个)而不是"3334444444",那么我会得到与13dff55c 13dff55c部分对应的正确输出(即else

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.

1 个答案:

答案 0 :(得分:6)

使用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’,表明该函数未被声明(因此假设返回int),因为您忘记了#include <stdlib.h>。添加缺失的#include会修复temp的值。

但您还应该查看为printf报告的警告并修复这些警告。