Search code examples
cvoid-pointersbit

Print bytes of a void pointer


If I create a void pointer, and malloc a section of memory to that void pointer, how can I print out the individual bytes 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 bytes that I just allocated.


Solution

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