0

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`
Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
Patrick Resal
  • 115
  • 2
  • 11
  • 1
    What do you mean only `write` is allowed? – Fiddling Bits Jan 13 '20 at 20:53
  • He means only write which takes a string argument is allowed. So he has to convert the pointer value to a string then output to `write` @Patrick Resai look into strtoll – Irelia Jan 13 '20 at 20:54
  • 1
    Probably something like [this](https://stackoverflow.com/a/26349454/10077), but use 16 for your radix instead of 10. And you'll need to account for the digits a-f. – Fred Larson Jan 13 '20 at 20:56
  • 1
    I'd recommend that you read the documentation for write(), try to solve the problem, and then update the question with your attempted code. – jarmod Jan 13 '20 at 20:56
  • 1
    The first thing to do is convert the pointer to a different type, one that can be used in mathematical expressions. That type is [uintptr_t](https://stackoverflow.com/questions/1845482/what-is-uintptr-t-data-type) – user3386109 Jan 13 '20 at 21:05
  • ITYM that you want to print the value of a pointer – M.M Jan 13 '20 at 21:07
  • https://stackoverflow.com/a/10933437/1505939 – M.M Jan 13 '20 at 21:10
  • 4
    Something wrong with sprintf()? – Lee Daniel Crocker Jan 13 '20 at 21:14
  • The C way to render a pointer value `p` in human-readable form is `printf("%p", (void*)p);`. The constraints "without using `printf()` and only `write()` is allowed" suggest this is a homework question. Please ensure StackOverflow gets credit. – mlp Jan 14 '20 at 16:49

1 Answers1

0

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));
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189