user3530012
user3530012

Reputation: 740

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";

Upvotes: 0

Views: 2745

Answers (1)

technusm1
technusm1

Reputation: 533

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]);
}

Upvotes: 1

Related Questions