I've been messing around with C today and don't understand the difference in outputs when I comment out the third buffer in this code:
#include <unistd.h>
#include <string.h>
#include <stdio.h>
void main() {
unsigned char letters[10];
memset(letters, 0x00, 10);
memset(letters, 0x41, 10);
printf(letters);
printf(" Total buffer len: %d bytes\n",strlen(letters));
char nletters[10];
memset(nletters, 0x00, 10);
memset(nletters, 0x42, 10);
printf(nletters);
printf(" Total buffer len: %d bytes\n",strlen(nletters));
int nums[10];
memset(nums, 0x00, 10);
memset(nums, 0x43, 10);
printf(nums);
printf(" Total buffer len: %d bytes\n",strlen(nums));
return 0;
}
The difference is with comments removed around the nums buffer:
AAAAAAAAAA�7ǝ�U Total buffer len: 16 bytes
BBBBBBBBBBAAAAAAAAAA�7ǝ�U Total buffer len: 26 bytes
And with the buffer left in:
AAAAAAAAAA Total buffer len: 10 bytes
BBBBBBBBBBAAAAAAAAAA Total buffer len: 20 bytes
CCCCCCCCCC��U Total buffer len: 14 bytes
What I don't get is:
How can commenting out the third buffer affect the size of the others?
What are the extra bytes at the end of the buffers and how can I lose/manage them (if I choose to concatenate the buffers)?
Why are the differences in the printed buffer size and initialized size not consistent when I choose whether to comment the third buffer?
Buffer 2 is supposed to be 10 bytes, why is it 20? I don't want it to be 20, I only asked for 10. I don't think that's unreasonable.