I was writing a generator for an old assignment that made a binary tree in-order and printed it to a binary file where then I could check that the nodes were written correctly using od in bash. I noticed that when the 2 char array carrying the values for the nodes was written it ended up taking 4 bytes in comparison to the expected 2 at most. Not only that but without fail every time the third node is written that extra 2 bytes is negative filled with 0xFFFF. When I remove the char array from the Node struct and all related code to it, whatever those extra bytes were disappeared completely. I was able to complete the assignment fine by ignoring that part of the file when read back but I'm still stumped why it was ever written in the first place. I will include my code and the output from 'od -x' after running it on the output file from making a tree with 10 nodes.
int32_t loc;
char value[2];
int32_t left;
int32_t right;
}Node;
char getRandUpper() {
return (char)('A' + (rand() % 26));
}
int main(int argc, char* argv[]) {
srand((unsigned int)time(NULL));
int numOfNodes = atoi(argv[2]);
char* fileName = argv[1];
FILE* filePtr = fopen(fileName, "wb");
Node biTree[numOfNodes];
for(int i = 0; i < numOfNodes; i++) {
biTree[i].loc = i;
if((i * 2) >= numOfNodes) {
biTree[i].left = -1;
biTree[i].right = -1;
} else {
biTree[i].left = (2 * i) + 1;
biTree[i].right = (2 * i) + 2;
}
for(int j = 0; j < 2; j ++) {
biTree[i].value[j] = getRandUpper();
printf("%c", biTree[i].value[j]);
printf("size of char array: %ld bytes\n", sizeof(biTree[i].value));
}
}
fwrite(biTree, sizeof(Node), numOfNodes, filePtr);
fclose(filePtr);
return 0;
}
Here is the output from od:
0000020 0001 0000 484f 0000 0003 0000 0004 0000
0000040 0002 0000 4652 ffff 0005 0000 0006 0000
0000060 0003 0000 4657 0000 0007 0000 0008 0000
0000100 0004 0000 4557 0000 0009 0000 000a 0000
0000120 0005 0000 4152 0000 ffff ffff ffff ffff
0000140 0006 0000 4a41 0000 ffff ffff ffff ffff
0000160 0007 0000 414a 0000 ffff ffff ffff ffff
0000200 0008 0000 4c41 0000 ffff ffff ffff ffff
0000220 0009 0000 504e 0000 ffff ffff ffff ffff
0000240
Anything to demystify this for myself would be appreciated. It's probably just my stupidity but who knows.