-
Bug
-
Resolution: Duplicate
-
P5
-
None
-
7
-
generic
-
generic
As compilers get more pedantic about ensuring correct use of types and format specifiers we run into issues when printing ptr values. The obvious way to print a pointer is to use %p but because %p differs in the actual format it uses (leading 0x or not) across platforms, we instead define a simple macro PTR_FORMAT, and in turn PTR32_FORMAT and PTRT64_FORMAT. But therein lies the problem because if we use:
#define PTR32_FORMAT "0x%08x"
And we print a pointer value the compiler will warn (eg):
error: format ‘%08x’ expects type ‘unsigned int’, but argument 2 has type ‘char*’
So to get rid of the warning we should use a pointer format specifier, but we can't so instead we cast the pointer type to intptr_t. But if we do just that we have eg:
char* str = "a string";
printf("ptr is " PTR_FORMAT "\n", (intptr_t) str);
which looks wrong, so we then change it to:
printf("ptr is " INTPTR_FORMAT "\n", (intptr_t) str);
which keeps everything happy, matches format specifier with type, but hides the fact that really we're printing a pointer and only works "right" because we use INTPTR_FORMAT as an alias for PTR_FORMAT!
#define PTR32_FORMAT "0x%08x"
And we print a pointer value the compiler will warn (eg):
error: format ‘%08x’ expects type ‘unsigned int’, but argument 2 has type ‘char*’
So to get rid of the warning we should use a pointer format specifier, but we can't so instead we cast the pointer type to intptr_t. But if we do just that we have eg:
char* str = "a string";
printf("ptr is " PTR_FORMAT "\n", (intptr_t) str);
which looks wrong, so we then change it to:
printf("ptr is " INTPTR_FORMAT "\n", (intptr_t) str);
which keeps everything happy, matches format specifier with type, but hides the fact that really we're printing a pointer and only works "right" because we use INTPTR_FORMAT as an alias for PTR_FORMAT!
- duplicates
-
JDK-8029996 Use __attribute__((format...)) for printf-style methods
-
- Closed
-