简体   繁体   English

为什么在此代码中打印出printf()?

[英]Why is printf() printing out in this code?

This simple code is puzzling me - I am deliberately printing out more integers than I passed to printf. 这个简单的代码使我感到困惑-我故意打印出比传递给printf的整数更多的整数。 I expected an error. 我预期会发生错误。 I got weird numbers - where are they coming from? 我有奇怪的数字-它们来自哪里?

#include <stdio.h>
/* learn arrays */
void main(){
    int pout;
    pout = 6;
    printf("%i %i %i\n%i %i %i\n%i %i %i\n", pout);
}

One example of the output: 输出的一个示例:

6 608728840 0
-885621664 -885543392 608728816
0 0 -889304251

The single digits do not change with repeated runs, but the large integers do. 单个数字不会随着重复运行而改变,但是大整数会改变。

It's one of printf string format vulnerability. 这是printf字符串格式漏洞之一。 You are trying to call more argument than there actually are, so printf takes whatever he can on the stack. 您正在尝试调用比实际更多的参数,因此printf会尽其所能。

It was (and still is) very used to exploit programs into exploring stacks to access hidden information or bypass authentication for example. 它曾经(现在仍然)非常常用于开发程序,以探索堆栈以访问隐藏信息或例如绕过身份验证。

Viewing the stack 查看堆栈

 printf ("%08x %08x %08x %08x %08x\\n"); 

This instructs the printf-function to retrieve five parameters from the stack and display them as 8-digit padded hexadecimal numbers. 这指示printf函数从堆栈中检索五个参数,并将它们显示为8位填充的十六进制数字。 So a possible output may look like: 因此,可能的输出如下所示:

40012980 080628c4 bffff7a4 00000005 08059c04

See this for a more complete explanation. 请参阅此内容以获得更完整的说明。

Because it's undefined behavior. 因为它是未定义的行为。 If the number of specifiers is larger than the number of matching parameters or their types are incompatible, the behavior is undefined. 如果说明符的数量大于匹配参数的数量,或者它们的类型不兼容,则行为不确定。

This qoute is from the c11 standard draft 此qoute来自c11标准草案

7.21.6.1 The fprintf function 7.21.6.1 fprintf函数

  1. The fprintf function writes output to the stream pointed to by stream, under control of the string pointed to by format that specifies how subsequent arguments are converted for output. fprintf函数在格式所指向的字符串的控制下,将输出写入流所指向的流,该字符串指定了如何转换后续参数以进行输出。 If there are insufficient arguments for the format, the behavior is undefined . 如果格式的参数不足,则行为未定义 If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored. 如果在保留参数的同时用尽了格式,则会对多余的参数进行评估(一如既往),否则将被忽略。 The fprintf function returns when the end of the format string is encountered. 当遇到格式字符串的结尾时,fprintf函数将返回。

  1. If a conversion specification is invalid, the behavior is undefined. 如果转换规范无效,则行为未定义。 282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined . 282) 如果任何参数都不是对应转换规范的正确类型,则该行为是undefined

I highlighted the relevant parts making them bold. 我强调了相关部分,使它们大胆。

int保留了一些RAM,但是您没有写任何东西,因此它向您显示RAM中某处随机的数字

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

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