简体   繁体   English

函数printf()的问题

[英]problem with function printf()

Here is my program: 这是我的程序:

#include <stdio.h>
int main()
{
    int a=0x09;
    int b=0x10;
    unsigned long long c=0x123456;
    printf("%x %llx\n",a,b,c);//in "%llx", l is lowercase of 'L', not digit 1
    return 0;
}

the output was: 输出为:

9 12345600000010

I want to know: 我想知道:

  1. how function printf() is executed? 函数printf()如何执行?
  2. what will happen if the number of arguments isn't equal to that of formats? 如果参数数量不等于格式数量会怎样?

please help me and use this program as an example to make an explanation. 请帮助我,并以该程序为例进行说明。

The problem is that your types don't match. 问题是您的类型不匹配。 This is undefined behavior. 这是未定义的行为。

Your second argument b does not match the type of the format. 您的第二个参数b与格式类型不匹配。 So what's happening is that printf() is reading past the 4 bytes holding b ( printf is expecting an 8-byte operand, but b is only 4 bytes). 因此,发生的情况是printf()读取了超过4个保留b的字节( printf期望有8个字节的操作数,但是b只有4个字节)。 Therefore you're getting junk. 因此,您会变得垃圾。 The 3rd argument isn't printed at all since your printf() only has 2 format codes. 因为您的printf()只有2个格式代码,所以根本不打印第3个参数。

Since the arguments are usually passed consecutively (and adjacent) in memory, the 4 extra bytes that printf() is reading are actually the lower 4 bytes of c . 由于参数通常在内存中连续(相邻)传递,因此printf()读取的4个额外字节实际上是c的低4个字节。

So in the end, the second number that's being printed is equal to b + ((c & 0xffffffff) << 32) . 因此最后,要打印的第二个数字等于b + ((c & 0xffffffff) << 32)

But I want to reiterate: this behavior is undefined . 但我要重申: 这种行为是不确定的 It's just that most systems today behave like this. 只是当今大多数系统的行为都像这样。

If the arguments that you pass to printf don't match the format specification then you get undefined behavior . 如果传递给printf的参数与格式规范不匹配,则将出现未定义的行为 This means that anything can happen and you cannot reason about the results that you happen to see on your specific system. 这意味着任何事情都可能发生,并且您无法推理在特定系统上看到的结果。

In your case, %llx requires and argument of type unsigned long long but you supplied an int . 在您的情况下, %llx需要,并且类型为unsigned long long参数,但是您提供了int This alone causes undefined behaviour. 仅此一项就导致不确定的行为。

It is not an error to pass more arguments to printf than there are format specificiers, the excess arguments are evaluated but ignored. 将更多的参数传递给printf并不是错误,而不是格式规范,多余的参数会被评估但会被忽略。

printf() increases a pointer to read an argument at a time according to the format. printf()根据格式增加一次读取参数的指针。 If the number of formatting arguments is larger than the number of parameters, then printf() will output data from unknown memory locations. 如果格式化参数的数量大于参数的数量,则printf()将从未知内存位置输出数据。 But if the number of parameters is larger than the number of formatting arguments, then no harm was done. 但是,如果参数的数量大于格式化参数的数量,则不会造成任何危害。 Eg gcc will warn you if the number of formatting arguments and parameters don't match. 例如,如果格式化参数和参数的数量不匹配,gcc会警告您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM