Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

memcpy not behaving as documented

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading