加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Re Legacy代码:格式’%d’需要类型为’int’的参数,但参数3的

发布时间:2020-12-16 01:52:44 所属栏目:安全 来源:网络整理
导读:我经常尝试使用最近的GCC构建大量旧的模拟器和磁盘和磁带归档工具.有些错误很容易解决,但我不是一个程序员. 我明白了: itstar.c: In function ‘addfiles’: itstar.c:194:4: warning: format ‘%d’ expects argument of type ‘int’,but argument 2 has
我经常尝试使用最近的GCC构建大量旧的模拟器和磁盘和磁带归档工具.有些错误很容易解决,但我不是一个程序员.

我明白了:

itstar.c: In function ‘addfiles’:
itstar.c:194:4: warning: format ‘%d’ expects argument of type ‘int’,but argument 2 has type ‘long unsigned int’ [-Wformat]
itstar.c:194:4: warning: format ‘%d’ expects argument of type ‘int’,but argument 3 has type ‘long unsigned int’ [-Wformat]

从这段代码片段:

/* add files to a DUMP tape */
/* output buffer must have been initialized with resetbuf() */
static void addfiles(int argc,char **argv)
{
    int c=argc;
    char **v=argv;

    while(c--) {
        addfile(argc,argv,*v++);
    }
    if(verify)
        printf("Approximately %d.%d' of tape usedn",count/bpi/12,(count*10/bpi/12)%10);
}

其中第194行是最后一行,从printf开始.

该文件是itstar.c,来自tapetools,代码为here.

尽管有警告,它仍会建立,但我更愿意知道如何预防它,
因此结果更有效,数据损坏的可能性更小.

拜托,我错过了什么,需要改变?

先感谢您.

解决方法

这是 undefined behavior,这意味着任何事情都可能发生,包括看似正常工作,然后在路上打破.

查看源代码,我们可以看到count和bpi都是unsigned long:

extern unsigned long bpi; /* tape density in bits per inch */
extern unsigned long count; /* count of tape frames written */

这些的正确格式说明符是%lu.

printf的第一个参数指定要打印的字符串,该字符串可以包含以%开头的转换说明符,通常指定后续参数的类型,因此在您的示例中:

"Approximately %d.%d' of tape usedn"
               ^^ ^^
               1  2

转换说明符1和2都是%d,这意味着printf将期望接下来的两个参数是int类型,但它们实际上是unsigned long类型.

如果我们看一下draft C99 standard第7.19.6.1节fprintf函数,它也涵盖了printf格式说明符,说:

If a conversion specification is invalid,the behavior is undefined.248) If any argument is not the correct type for the corresponding conversion specification,the behavior is undefined.

所以你需要修复不正确的格式说明符,你的警告就会消失,你将回到明确定义的行为领域.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读