没有参数的`printf("%p")`是什么意思 [英] What is the meaning of `printf("%p")` without arguments

查看:100
本文介绍了没有参数的`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")`是什么意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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