print bits of a void pointer

﹥>﹥吖頭↗ 提交于 2020-01-11 11:18:15

问题


If I create a void pointer, and malloc a section of memory to that void pointer, how can I print out the individual bits that I just allocated?

For example:

void * p;
p = malloc(24);
printf("0x%x\n", (int *)p);

I would like the above to print the 24 bits that I just allocated.


回答1:


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).




回答2:


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");



回答3:


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);



回答4:


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?




回答5:


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




回答6:


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?



来源:https://stackoverflow.com/questions/14656375/print-bits-of-a-void-pointer

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