I know there's tons of these and it's probably a simple question, but I can't seem to figure it out :(
char * char_buffer = (char *) malloc(64);
printf("%x\n", char_buffer);
memset(char_buffer,
0,
64);
printf("%x\n", char_buffer);
Output :
50000910
50000910
Why isn't char_buffer zero'd? Can someone explain what's happening?
You are confused about the difference between a pointer and space being pointed to.
Your code doesn't zero the pointer. It zeroes the space being pointed to. The memset
function behaves that way. In fact you would not want to zero the pointer, as then it would no longer point to the memory you allocated.
Your printf
statement attempts to print the pointer's value, which is the address of the space being pointed to. Not the contents of the space being pointed to.
Actually the printf statement causes undefined behaviour, because you mismatched format specifiers. Your compiler should have warned about this.
Here is some correct code:
printf("The buffer's address is %p\n", char_buffer);
printf("The buffer contains: %02X %02X %02X ...\n",
(unsigned char)char_buffer[0],
(unsigned char)char_buffer[1],
(unsigned char)char_buffer[2]);
To use the %X
specifier you must pass non-negative values in, which is why the cast is necessary. You could declare the buffer as unsigned char *
instead, in which case the cast would not be necessary.