Q:

strlen not giving correct length after memcpy in C

I'm quite confused in this problem. Here's the code:
char str[256];
memcpy(&str[0], "Q", 1);
memcpy(&str[1], "5", 1); // everything fine so far
int16_t lenQ = 22;
memcpy(&str[2], (char*)&lenQ, sizeof(int16_t));
str[2 + sizeof(int16_t)] = (char) NULL;
printf("%i\n", strlen(str)); // prints out 2??

Logically the length of str should be 4, but it's only two. To make things even more confusing, this works:
int16_t raw = 0;
memcpy(&raw, &str[2], 2);
printf("%i\n", raw) // prints out 22 as expected

So the size of the str is incorrect, but I can still actually access the "out of bounds" value. Have I understood this incorrectly? From what I understand, the str-array should look like this internally:
'Q', '5', /* 22 in bytes, which is 2 in this case */

Should I even get the length of the array like that or am I doing something completely wrong?

A:

An int16_t in memory could be either \0\x16 or \x16\0 based on the endianness of your machine. In your case it is \0\x16 and the memory at str will end up containing "Q5\0\x16". Hence strlen(str) correctly returns 2, as the \0 byte terminates the C-style string.
If you want the result to be "Q522", the lenQ variable of type int16_t should have a value of 12850 which (for all reasonable CPU architectures) is stored in memory as two bytes with the values 50 (0x32 in base 16) or the ASCII characters '2'.

