简体   繁体   English

命令printf出现一个奇怪的问题

[英]A weird problem with command printf

I am using Simple Scalar toolset to run some simulations on cache associativity. 我正在使用简单标量工具集在缓存关联性上运行一些模拟。 And I am seeing some strangest behavior with printf function. 而且我发现printf函数有一些最奇怪的行为。 Here is the code snippet: 这是代码片段:

printf(" Name: %s %d %d %d \n", name, nsets, cp->set_shift, cp->set_mask);
printf(" Name: %s %d %d %d \n", name, cp->set_mask, nsets, cp->set_shift);

The printf lines are one after another, no other code in between. printf行是一个接一个的,中间没有其他代码。 And here is the output: 这是输出:

 Name: dl1 128 5 127
 Name: dl1 127 0 128

The output of second printf is wrong. 第二个printf的输出错误。 The output of the second printf should be : 第二个printf的输出应为:

Name: dl1 127 128 5

Changing the relative order of printf statements does not change the output. 更改printf语句的相对顺序不会更改输出。 What part of printf I am missing to understand?? 我错过了printf的哪一部分?

With regards Newbie 关于新手

Go look at the variable declarations. 去看看变量声明。 My guess is somebody is a short or long , not an int . 我的猜测是某人是short还是long ,而不是int Since printf can't check what you pass for validity, it decides how many bites to grab from the stack based on the % signs. 由于printf无法检查传递给您的有效性,因此它会根据%符号决定从堆栈中抓取多少位。 If your args don't agree with the format, not a compile error, but garbage can come out. 如果您的参数与格式不符,则不是编译错误,但可能会产生垃圾。

I'd guess you have a mis-match between the type you're passing and the type you're telling print that you're passing. 我猜您在传递的类型和告诉打印要传递的类型之间不匹配。 Specifically, it looks like cp->set_mask is some type larger than int. 具体来说,看起来cp-> set_mask比int大一些。 Since you've told printf that it's an int, it's taking the first sizeof(int) bytes as the first int, and then the next sizeof(int) bytes as if it were nsets (and since you're apparently on a little-endian machine, those bytes all contain 0). 由于您已经告诉printf它是一个int,因此它将第一个sizeof(int)字节作为第一个int,然后将下一个sizeof(int)字节当作nset(并且由于您显然在使用- endian机器,这些字节都包含0)。 Note, in particular, that after the 0 comes the 128 that the first prints says is the value of nsets . 特别要注意的是, 0 之后是第一个打印出的128,即nsets的值。

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

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