print bits of a void pointer

旧城冷巷雨未停 提交于 2019-12-02 06:57:47
size_t size = 24;
void *p = malloc(size);

for (int i = 0; i < size; i++) {
  printf("%02x", ((unsigned char *) p) [i]);
}

Of course it invokes undefined behavior (the value of an object allocated by malloc has an indeterminate value).

You can't - reading those bytes before initializing their contents leads to undefined behavior. If you really insist on doing this, however, try this:

void *buf = malloc(24);
unsigned char *ptr = buf;
for (int i = 0; i < 24; i++) {
    printf("%02x ", (int)ptr[i]);
}

free(buf);
printf("\n");
void print_memory(void *ptr, int size)
{ // Print 'size' bytes starting from 'ptr'
    unsigned char *c = (unsigned char *)ptr;
    int i = 0;

    while(i != size)
        printf("%02x ", c[i++]);           
}

As H2CO3 mentioned, using uninitialized data results in undefined behavior, but the above snipped should do what want. Call:

print_memory(p, 24);
LihO

void* p = malloc(24); allocates 24 bytes and stores the address of first byte in p. If you try to print the value of p, you'll be actually printing the address. To print the value your pointer points to, you need to dereference it by using *. Also try to avoid void pointers if possible:

unsigned char *p = malloc(24);
// store something to the memory where p points to...
for(int i = 0; i < 24; ++i)
    printf("%02X", *(p + i));

And don't forget to free the memory that has been allocated by malloc :)

This question could help you too: What does "dereferencing" a pointer mean?

malloc allocates in bytes and not in bits. And whatever it is, your printf is trying to print an address in the memory.

The malloc allocates bytes.

 for (i = 0; i < 24; ++i) printf("%02xh ", p[i]);

would print the 24 bytes. But if cast to an int, you'll need to adjust the loop:

 for (i = 0; i < 24; i += sizeof(int)) printf("%xh", *(int *)&p[i]);

But then, if you know you want an int, why not just declare it as an int?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!