I of course know it used to output pointer with arguments.
I read book Writing Secure Code by Michael Howard and David LeBlanc.
One program in book demonstrates how stack overflow works by strcpy()
Note printf()
without arguments.
#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;
}
The result is
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
What is the meaning of printf("%p")
inside code? Why it can print the content of stack?
Functions belonging to the printf function family have the type specifiers "%p" and "%x". "x" and "X" serve to output a hexadecimal number. "x" stands for lower case letters (abcdef) while "X" for capital letters (ABCDEF). "p" serves to output a pointer.
%p is for printing a pointer address. 85 in decimal is 55 in hexadecimal. On your system pointers are 64bit, so the full hexidecimal representation is: 0000000000000055.
%p expects the argument to be of type (void *) and prints out the address. Whereas %x converts an unsigned int to unsigned hexadecimal and prints out the result.
%u is used for unsigned integer. Since the memory address given by the signed integer address operator %d is -12, to get this value in unsigned integer, Compiler returns the unsigned integer value for this address.
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");
is undefined behaviour.
As per the printf()
description in the standard, if there are insufficient arguments for supplied format, it's UB.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With