Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the format of %p and %x different in a format string?

When printing a hexadecimal value (%x) and an address (%p), the format is slightly different. The printed value does not start with 0x in the case of a hexadecimal value:

int main()
{
     int x = 0x1234;
     printf("Value of x: %x\n", x);
     printf("Address of x: %p\n", (void*)&x);
}

yields (gcc):

Value of x: 1234
Address of x: 0xffb0fbfc

Why is the 0x forced on you in the case of an address?

I guess it boils down to the standard.

What would be the correct way to print an address without the 0x if i wanted to? The %p is not only a %x with an added 0x right?

like image 682
Martin G Avatar asked Feb 25 '15 10:02

Martin G


People also ask

What is the difference between %D and %P in C?

Originally Answered: What are the actual differences between %d, %u and %p format specifiers used in C to print the memory address of a variable? As you already explained %d is used for signed integers, while %u is for unsigned integers. %p is used to print pointer addresses.

What is the difference between %D and %ld?

%d is for signed int, Use %u specifically for unsigned int. Long and int types are same. %ld is for long int. There wont be any error like access violation, printf will treat the argument as signed, that might display the output differnetly that what you expected.

What causes format string vulnerability?

The Format String exploit occurs when the submitted data of an input string is evaluated as a command by the application.

What does %P in C mean?

%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.


3 Answers

p

The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printable characters, in an implementation-defined manner.

reference

like image 73
auselen Avatar answered Sep 28 '22 12:09

auselen


The output format for %p is implementation specific. Not every C implementation is on machines with addresses of the same size as int. There is the intptr_t from <stdint.h>

like image 28
Basile Starynkevitch Avatar answered Sep 28 '22 13:09

Basile Starynkevitch


The %p is not only a %x with an added 0x right?

No.. %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.

And coming to what %p does is implementation defined but the standard just says that %p expects void* argument else the behavior is undefined.

like image 45
Gopi Avatar answered Sep 28 '22 13:09

Gopi