print bits of a void pointer

后端 未结 6 2103
[愿得一人]
[愿得一人] 2021-01-23 01:52

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:



        
相关标签:
6条回答
  • 2021-01-23 02:19
    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).

    0 讨论(0)
  • 2021-01-23 02:28

    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?

    0 讨论(0)
  • 2021-01-23 02:30

    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");
    
    0 讨论(0)
  • 2021-01-23 02:35

    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?

    0 讨论(0)
  • 2021-01-23 02:38

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

    0 讨论(0)
  • 2021-01-23 02:40
    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);
    
    0 讨论(0)
提交回复
热议问题