Search code examples
cstringbytestrcat

Prefix unsigned char pointer array with two 0x00 bytes


If for example I have an unsigned char *str with the values 0x68 0x65 0x6C 0x6C 0x6F, how can I prefix this array with two null bytes so the array would become [0x00 0x00] 0x68 0x65 0x6C 0x6C 0x6F ([] = added bytes)?

I have tried with strcat but this doesn't produce the desired result, I imagine because 0x00 bytes are treated as string terminators.


Solution

  • The function strcat is intended for handling strings, i.e. zero-terminated character arrays. Since your array is not zero-terminated, you should not use this function.

    Instead, you can use the memmove and memset functions, if you want to avoid hand-coding the movement. However, you need to declare the str array with an appropriate (larger) size (to accomodate the added bytes). So, for example:

    unsigned char str[7] = { 0x68, 0x65, 0x6C, 0x6C, 0x6F, }; // Note: size must be at least 7
    //.. some code
    memmove(str+2, str, 5); // Shift along by two bytes (see note, below)
    memset(str, 0, 2);      // Add the two 'prefix' zeros
    

    Note that the memmove function is safe with overlapping buffers (bolding mine):

    Copies the values of num bytes from the location pointed by source to the memory block pointed by destination.
    Copying takes place as if an intermediate buffer were used, allowing the destination and source to overlap.

    However, this only applies to the function memmove, not the function memcpy. With the function memcpy, it is not safe to have overlapping buffers.

    Also, please note that unsigned char *str does not declare an array (though you can use similar syntax for string literals). You need to use the (now corrected) version of the posted code.