没有参数的`printf("%p")`是什么意思

编程入门 行业动态 更新时间:2024-10-25 10:26:15
本文介绍了没有参数的`printf("%p")`是什么意思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我当然知道它曾经输出带参数的指针.

I of course know it used to output pointer with arguments.

我阅读了 Michael Howard 和 David LeBlanc 合着的Writing Secure Code一书.

I read book Writing Secure Code by Michael Howard and David LeBlanc.

书中的一个程序通过strcpy()

注意 printf() 不带参数.

#include <stdio.h> #include <string.h> void foo(const char* input) { char buf[10]; //What? No extra arguments supplied to printf? //It's a cheap trick to view the stack 8-) //We'll see this trick again when we look at format strings. printf("My stack looks like:\n%p\n%p\n%p\n%p\n%p\n% p\n\n"); //Pass the user input straight to secure code public enemy #1. strcpy(buf, input); printf("%s\n", buf); printf("Now the stack looks like:\n%p\n%p\n%p\n%p\n%p\n%p\n\n"); } void bar(void) { printf("Augh! I've been hacked!\n"); } int main(int argc, char* argv[]) { //Blatant cheating to make life easier on myself printf("Address of foo = %p\n", foo); printf("Address of bar = %p\n", bar); if (argc != 2) { printf("Please supply a string as an argument!\n"); return -1; } foo(argv[1]); return 0; }

结果是

C:\Secureco2\Chapter05>StackOverrun.exe Hello Address of foo = 00401000 Address of bar = 00401045 My stack looks like: 00000000 00000000 7FFDF000 0012FF80 0040108A <-- return address 00410EDE Hello Now the stack looks like: 6C6C6548 <-- 'l','l','e','h' 0000006F <-- 0, 0, 0, 'o' 7FFDF000 0012FF80 0040108A 00410EDE

代码里面的printf("%p")是什么意思?为什么它可以打印堆栈的内容?

What is the meaning of printf("%p") inside code? Why it can print the content of stack?

推荐答案

一般来说,%p 是一个 格式说明符打印指针(地址值),预期的参数是一个指向void类型的指针.

In general, %p is a format specifier to print the pointer (address value), the argument expected is a pointer to void type.

也就是说,在您的代码中,

That said, in your code,

printf("My stack looks like:\n%p\n%p\n%p\n%p\n%p\n% p\n\n");

是未定义行为.根据标准中的 printf() 描述,如果提供的格式参数不足,则为 UB.

is undefined behaviour. As per the printf() description in the standard, if there are insufficient arguments for supplied format, it's UB.

引用标准,C11,章节 §7.21.6.1

To quote the standard, C11, chapter §7.21.6.1

[...] 如果格式的参数不足,则行为是不明确的..[...]

[...] If there are insufficient arguments for the format, the behavior is undefined. .[...]

代码片段对产生任何有效输出的保证为零.

The code snippet has zero guarantee to produce any valid output.

更多推荐

没有参数的`printf("%p")`是什么意思

本文发布于:2023-08-01 04:21:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1265167.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   printf   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!