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?
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.
%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.
The Format String exploit occurs when the submitted data of an input string is evaluated as a command by the application.
%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
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
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>
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.
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