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:
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).
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?
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");
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?
malloc
allocates in bytes and not in bits. And whatever it is, your printf
is trying to print an address in the memory.
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);