Can I print an address stored in a pointer using write function only ? (from unistd.h lib).
int c = 6;
void *ptr = &c;
printf("%p",ptr);
I'd like to get the same results as the code above using write not printf.
CodePudding user response:
You can simply format the address into a char buffer on your own and pass it to write
.
Normally you would just use sprintf
to do that but if you don't like printf
you might not like sprintf
, too.
Nevertheless I will show that first:
int c = 6;
void *ptr = &c;
char outbuf[2*sizeof(void*) 1];
sprintf("%x", p);
write(fd, outbuf, strlen(outbuf));
Without sprintf
and with MCVE:
#include <stdio.h>
#include <stdint.h>
int main()
{
int c = 6;
void *ptr = &c;
static const char hex_digits[]="0123456789abcdef";
size_t addr_size = sizeof (void*);
char outbuf[2*addr_size 1];
int i;
uintptr_t val =(intptr_t) ptr;
int nibble;
for (i = addr_size - 1; i >= 0; i--)
{
nibble = val % 0x10;
val /= 0x10;
outbuf[2*i 1] = hex_digits[nibble];
nibble = val % 0x10;
val /= 0x10;
outbuf[2*i] = hex_digits[nibble];
}
outbuf[2*addr_size] = 0;
printf("%s\n", outbuf);
// replace with write(fd, outbuf, strlen(outbuf)) for your needs
return 0;
}