7

I'm currently reading Hacking the art of exploitation and there is an example on there that I cannot seem to get correct. Attempting to compile results in the error:

./addressof.c: In function ‘main’:
./addressof.c:8:4: warning: format ‘%x’ expects argument of type ‘unsigned int’,
but argument 2 has type ‘int *’ [-Wformat]


#include <stdio.h>
int main() {
   int int_var = 5;
   int *int_ptr;

   int_ptr = &int_var; // Put the address of int_var into int_ptr.

   printf("int_ptr = 0x%08x\n", int_ptr);
   printf("&int_ptr = 0x%08x\n", &int_ptr);
   printf("*int_ptr = 0x%08x\n\n", *int_ptr);

   printf("int_var is located at 0x%08x and contains %d\n", &int_var, int_var);
   printf("int_ptr is located at 0x%08x, contains 0x%08x, and points to %d\n\n",
      &int_ptr, int_ptr, *int_ptr);
}

I understand where the error is, I'm just not sure how to fix this.

bigl
  • 1,063
  • 3
  • 13
  • 23

1 Answers1

16

The format specifier for pointer is %p, not %x. (See here)

MByD
  • 135,866
  • 28
  • 264
  • 277
  • Thank you very much, another quick question if you please. I'm getting just one more error - warning: format ‘%p’ expects argument of type ‘void *’, but argument 2 has type ‘int’ [-Wformat] What does this mean? Why does it expect type void? – bigl Mar 14 '12 at 22:00
  • 2
    @bigl That's because you're probably trying to print `*int_ptr` (which is an `int`) using the `%p` format specifier. `int_ptr` and `&int_ptr` are pointers and must be printed using `%p`, but the *value that the pointer is pointing to* is an integer and must be printed using `%d` – Praetorian Mar 14 '12 at 22:03
  • 2
    @bigl: You must cast any pointer to void pointer when passing it variadically through to `printf`: `printf("%p", (void*)(&x));`. Different pointer types are not required to be laid out the same way, but they *are* guaranteed to be convertible losslessly to `void*`. – Kerrek SB Mar 14 '12 at 22:05
  • I'll add that, at in least as of Xcode 4.4.1, you must use `%8p` instead of `%08p` (The leading zero is not supported for the specifier `p`). – Nicolas Miari Aug 29 '12 at 11:50