1

I am processing several chunks of byte arrays (uint_8) and append them to a string (my_string). For efficiency purposes, I have reserved more than enough bytes for my string by

my_string.reserve(more_than_enough_bytes);

I am trying to append each chunk as shown in the following function:

bool MyClass::AppendToMyString(uint_8* chunk, size_t chunk_num_bytes) {
  memcpy(const_cast<uint_8*>(my_string.data()), chunk, chunk_num_bytes);
  return true;
}

But the problem is that memcpy does not update my_string size. So, next time when this function is called, I do not where the last element was, other than using a separate variable for it. Any ideas?

4
  • You should use the my_string.append method, that's what it is designed for. my_string.append(chunk, chunk_num_bytes); You'll probably need a cast from uint_8* to char* Commented Jul 12, 2019 at 21:02
  • I'm surprised memcpy(my_string, chunk, chunk_num_bytes); compiles. What type is my_string? I've been assuming std::string but maybe not. Commented Jul 12, 2019 at 21:06
  • Use std::string::append. Overload 4 from that page should optimize to a memcpy for you. Commented Jul 12, 2019 at 21:09
  • string's size and length methods are guaranteed to be constant complexity. This means when you call size, string cannot run off and count the number of characters before the first null. It needs to be able to set the size as the string is modified. Since memcpy doesn't know it's operation on a string, it just sees an address it's supposed to write to, it cannot update the string's size. Commented Jul 12, 2019 at 21:18

1 Answer 1

2

std::string has an append method which will take care of this. Something along the lines of:

void append_chunk (std::string &s, const uint8_t* chunk, size_t chunk_num_bytes)
{
    s.append ((char *) chunk, chunk_num_bytes);
}

Live demo

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

Comments

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.