1

I have a unsigned char array like this:

unsigned char myArr[] = {100, 128, 0, 32, 2, 9};

I am using reinterpret_cast to covert it to const char* as I have to pass a const char* to a method. This information is then sent over grpc and the other application (erlang based recieves it and stores it in a erlang Bin). But what I observe is the Erlang application only received <<100, 128>> and nothing after that. What could be causing this? Is it the 0 in the character array that is the problem here? Could someone explain how to handle the 0 in an unsigned char array? I did read quite a few answers but nothing clearly explains my problem.

3
  • How do you perform the conversion? Commented Sep 23, 2020 at 10:16
  • 3
    "What could be causing this" - someone using strlen for their buffer length-to-send calculation. Commented Sep 23, 2020 at 10:27
  • please provide a minimal reproducible example Commented Sep 23, 2020 at 11:47

1 Answer 1

4

What could be causing this? Is it the 0 in the character array that is the problem here?

Most likely, yes.

Probably one of the functions that the pointer is passed to is specified to accept an argument which points to a null terminated string. Your array happens to incidentally be null terminated by containing null character at index 2 which is where the string terminates. Such function would typically only have well defined behavior in case the array is null terminated, so passing pointer to arbitrary binary that might not contain null character would be quite dangerous.

Could someone explain how to handle the 0 in an unsigned char array?

Don't pass the array into functions that expect null terminated strings. This includes most formatted output functions and most functions in <cstring>. The documentation of the function should mention the pre-conditions.

If such functions are your only option, then you can encode the binary data in a textual format and decode it in the other end. A commonly used textual encoding for binary data is Base64 although it is not necessarily the most optimal.

Sign up to request clarification or add additional context in comments.

3 Comments

This function is an auto-generated one after compilation of one .proto file.
@Purdgr8 What is "this function"?
The function to which I have to pass the array. So, I am not sure what options I am left with. As for the encoding that you suggest, it would mean adding some decoding mechanism in the other application. Unfortunately, I am not allowed to change the other side of the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.