为什么不的gcc -Wformat警告printf的%D于一个unsigned int? [英] Why doesn't gcc -Wformat warn about printf %d on an unsigned int?

查看:3918
本文介绍了为什么不的gcc -Wformat警告printf的%D于一个unsigned int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的程序是未定义行为:

 的#include<&stdio.h中GT;INT主要(无效)
{
    unsigned int类型X = -100; //这是罚款,成为UINT_MAX - 100
    的printf(%d个\\ N,X); //这是不确定的行为。
    返回0;
}


  

C99 7.19.6.1p8状态%d个期望一个int参数。


  
  

C99 7.19.6.1p9指出:如果任何参数类型不正确的
  相应的转换规范,行为
  未定义


不过,海湾合作委员会 -Wformat (它是包含在 -Wall )将不会抱怨上面的程序,为什么?这是一个bug,或故意的不作为?

从海湾合作委员会手册页:

  -Wformat

检查电话的printfscanf函数等,以确保提供的参数必须指定适当的格式字符串类型,并在格式字符串指定的转换意义


解决方案

我最好的猜测是,警告将被跳过,因为UB可以说是由的值调用的,而不是由单纯的类型。 的va_arg 允许,只要该值在两个符号和无符号类型重新presentable符号性的不匹配。然而,的printf 和朋友不在的va_arg 的条件和标准规定指定的任何类型不匹配的结果UB,但是这可能是标准的错误。否则,的printf(%X,1); 将调用UB。见我的问题上的题目是:

是否printf的(QUOT;%X",1)?未定义行为

The following program has undefined behavior:

#include <stdio.h>

int main(void)
{
    unsigned int x = -100; // This is fine, becomes UINT_MAX - 100
    printf("%d\n", x); // This is undefined behavior.
    return 0;
}

C99 7.19.6.1p8 states %d expects an int argument.

C99 7.19.6.1p9 states "If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined."

However, gcc -Wformat (which is included with -Wall) will not complain about the above program, why? Is this a bug, or a deliberate omission?

From the gcc manpage:

-Wformat

Check calls to "printf" and "scanf", etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense

解决方案

My best guess is that the warning is skipped because the UB is arguably invoked by the value and not merely by the type. va_arg allows the signedness to mismatch as long as the value is representable in both the signed and unsigned type. However, printf and friends are not specified in terms of va_arg and the standard states that any type mismatch results in UB, but this is probably a bug in the standard. Otherwise, printf("%x",1); would invoke UB. See my question on the topic:

Does printf("%x",1) invoke undefined behavior?

这篇关于为什么不的gcc -Wformat警告printf的%D于一个unsigned int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆