icecrime <ic******@gmail.comwrote:
I have a small interrogation concerning pointer to integer conversion:
how is it possible to safely and portably print a memory address ?
You use printf("%p", (void *)your_pointer).
From what I understand (according to FAQ 4.14), conversion from pointer to
integral is never never guaranteed. But (correct me if I'm wrong) some
kind of conversion _is_ necessary in order to print the numeric value.
True, but there's the problem: there is not necessarily a meaningful
numeric value for pointers. Not all computers have a flat memory space.
I have taken a look to the gnu libc printf implementation, and it
appears that the void * is being casted into the largest available
integer type. Do I have a standard and portable way to know about this
"largest integer type" ?
Yes and no. In C89, the largest (unsigned, which is what you want)
integer type is unsigned long. This may not be large enough to represent
all pointer values, though.
In C99, the situation is even more complex. The largest unsigned integer
is uintmax_t, which is required to exist in <stdint.h>; since this must
be at least as large as an unsigned long long, it is more likely to be
large enough for a pointer.
There is also an even better choice in the same header: uintptr_t. A
void pointer can be converted to this type and back without changing
value. The problem with this type is that it's optional. You can find
out if your implementation has it by checking if UINTPTR_MAX is #defined
in <stdint.h>.
For both these types, you can find macros needed to print them safely in
<inttypes.h>; if you #include that header, it also #includes <stdint.h>,
so you don't need to do that as well.
In the end, though, I'd just go with casting the pointer to (void *) and
using "%p". That's portable everywhere.
Richard