Search code examples
c++arraysmemcpy

How does size work with memcpy?


My question relates to how safe the following code is:

#define ARRAY_SIZE 10

std::array<BYTE, ARRAY_SIZE> myArray;
char* string = "this_sentence_is_longer_than_10_bytes"

memcpy(&myArray, string, ARRAY_SIZE);

Result: myArray is filled [0-9] with "this_sente"

In terms of it being safe, I need to know what is happening to the rest of 'string'. Is it being ignored completely due to the size given or is it being thrown off the end of the array?

edit: I now have

#define ARRAY_SIZE 10

std::array<BYTE, ARRAY_SIZE> myArray;
char* string = "this_sentence_is_longer_than_10_bytes"

if (strlen(string) < ARRAY_SIZE)
{
    BYTE clearArray[ARRAY_SIZE] = {0};
    memcpy(&myArray, clearArray, ARRAY_SIZE);
    memcpy(&myArray, string, strlen(string));
}
else
{
    memcpy(&myArray, string, ARRAY_SIZE);
}

It now pads out the std:array with zeroes if the string is shorter than 10 characters, otherwise it uses the initial method.


Solution

  • The rest of the string constant gets ignored, as if it's not there. memcpy stops as soon as it reaches size bytes.

    Note that although it is safe to pass a memory block that is larger than size to memcpy, passing a block that is shorter triggers undefined behavior. For example, if you pass string that has fewer than nine characters, memcpy will copy invalid characters past the end of the string into myArray.