【发布时间】:2014-04-26 14:17:14
【问题描述】:
我正在通过此链接在线阅读以下代码: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");
取自这段代码的sn-p:
/*
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;
}
我知道 %p 是指针的格式化程序,但是为什么格式化程序后面没有值?这里实际打印了哪些值?如果它正在打印提供给 foo 函数的参数的地址,那么为什么有 5 个 '%p' 以及为什么不是所有的 '%p' 都格式化相同的值?
非常感谢。
【问题讨论】:
-
不是你的主要观点,但“foo 的地址”行也会导致未定义的行为 -
%p仅用于打印void *,您甚至可能无法将函数指针转换为如果你尝试过。 -
我认为常规 C 函数指针可以转换为
void*。我知道指向成员函数的 C++ 指针更复杂,但如果无法转换常规函数指针,它会破坏 C 兼容性。