I need to print the address of a pointer (basically recoding %p
) but without using printf()
and only write()
is allowed.
How can I do it? Could you give me some hints?
For example :
printf("%p", a);
result :
0x7ffeecbf6b60`
I need to print the address of a pointer (basically recoding %p
) but without using printf()
and only write()
is allowed.
How can I do it? Could you give me some hints?
For example :
printf("%p", a);
result :
0x7ffeecbf6b60`
For your purpose, you just need to convert the pointer value to hex representation and write that to the POSIX file descriptor using the write
system call:
#include <stdint.h>
#include <unistd.h>
/* output hex representation of pointer p, assuming 8-bit bytes */
int write_ptr(int hd, void *p) {
uintptr_t x = (uintptr_t)p;
char buf[2 + sizeof(x) * 2];
size_t i;
buf[0] = '0';
buf[1] = 'x';
for (i = 0; i < sizeof(x) * 2; i++) {
buf[i + 2] = "0123456789abcdef"[(x >> ((sizeof(x) * 2 - 1 - i) * 4)) & 0xf];
}
return write(fd, buf, sizeof(buf));
}