简体   繁体   中英

How to copy a block of memory containing null terminator in c++

I have converted an image to byte array in C# and have sent it over TCP to a server application written in C++.

Now I want to copy this byte array to another block of memory. I've tried memcpy() function but the problem is memcpy copy the memory block until it reaches a null terminator ('\\0'), and the byte array contains many of null terminators and I want them to be copied too.

Update

For simplicity I've converter the string "Hello\\0"World\\0" in C# to a byte array using the following statement:

string s = "Hello\0"World\0";
byte[] bytes = Encoding.UTF8.GetBytes(s);

I receive the bytes in an unsigned char* in c++ and copy it to another char pointer like this:

char *chars = new char[12];
memcpy(chars , recvChar, MESSAGE_12);

but the char* results in "Hello";

According to this

The function memcpy() does not check for any terminating null character in source - it always copies exactly num bytes. You sure it was memcpy?

You can use something like this to print chars array (printf terminates at NULL character):

for (int i = 0; i < 12; i++) //12 is the size of chars, I assume
{
    if (chars[i]!=NULL) //if you hit a '\0', ignore it
        printf("%c", chars[i]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM