Search code examples
c++g++c++20memcpy

memcpy not behaving as expected


I have a char array with a fixed length of 2 and I want to read a 2 byte subsection of data from a buffer of size 1024 starting from index '0'.

char signature[2];
char arr[1024]; // this is populated with data
memcpy(&signature, &arr[0], sizeof this->signature);

If I manually look at the first two characters in arr with a for loop

for (int i = 0; i < 2; i++) {
    std::cout << arr[i] << std::endl;
}

it outputs:

B
M

however when I read signature:

std::cout << signature << std::endl
std::cout << sizeof signature << std::endl;

it comes up with this:

BM�
3

I don't understand what's going on. My solution complies with all online examples of how to utilize memcpy.

build:

g++ -std=c++2a -I./include src/*.cpp -o res

I don't understand what's going on. My solution complies with all online examples of how to utilize memcpy.


Solution

  • The memcpy works but your code for displaying the result is incorrect.

    Passing a char array to std::cout only works if the array contains a null-terminated string.

    To display a char array that does not contain a null terminated string you could do something like:

    for (char ch : signature)
        std::cout << ch;
    std::cout << '\n';