在printf中使用%p?

Jer*_*ang 3 c memory assembly

我通过以下链接在线阅读以下代码:http://www.cse.scu.edu/~tschwarz/coen152_05/Lectures/BufferOverflow.html

我对此行中%p的使用感到困惑:

 printf("Now the stack looks like:\n%p\n%p\n%p\n%p\n%p\n%p\n\n");
Run Code Online (Sandbox Code Playgroud)

这是从这段代码中获取的:

 /*
  StackOverrun.c
  This program shows an example of how a stack-based 
  buffer overrun can be used to execute arbitrary code.  Its 
  objective is to find an input string that executes the function bar.
*/

#pragma check_stack(off)

#include <string.h>
#include <stdio.h> 

void foo(const char* input)
{
    char buf[10];

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

    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;
}
Run Code Online (Sandbox Code Playgroud)

我知道%p是指针的格式化程序,但为什么格式化程序后面没有值?这里实际打印的是什么值?如果它打印提供给foo函数的参数的地址,那么为什么有5'%p'以及为什么不是所有的'%p'都格式化相同的值?

非常感谢.

Sti*_*sis 8

这是利用未定义的行为.

故意不向printf提供值,将从va_arg堆栈中拉出任意值以进行打印.这不是正确的代码.实际上,看起来这段代码片段正试图解释黑客攻击技术,这些技术通常会利用未定义行为发生时出现的故障.

  • 因此,在某些体系结构(包括64位模式下的x86)上,它将值从寄存器中拉出,而不是(有时甚至是)从堆栈中拉出。参见例如http://en.wikipedia.org/wiki/X86_calling_conventions (4认同)