1

I am dealing with a buffer in memory which is being read as protobuf. I need to deserialize it. The content of this protobuf contains a string which may or may not have null character inside the string. For example, the string could be something like this : "name\0first". If I have the input like this, the string that I can deserialize always looks like "name" since the string class drops the part after null character.

How can I access the complete string in this case? String length function obviously do not help in this case.

Santanu C
  • 1,362
  • 3
  • 20
  • 38
  • You are mistaken -- `string::length()` function works correctly, even if the std::string contains NULLs. You need to show us what you're doing now to access or print this string, and then we can show you how to properly obtain the contents of the string. – PaulMcKenzie Feb 27 '15 at 23:00
  • 1
    std::string can accept strings with embedded NUL characters. – jbruni Feb 27 '15 at 23:08
  • @PaulMcKenzie: I wrote a trivial test program : string s("name\0first"); cout << s << endl; cout << s.length() << endl; s.length() does not show 9. It is 4. – Santanu C Feb 28 '15 at 01:18
  • @SantanuC you have to use the constructor that takes a length argument if your string contains null characters. – Axel Mar 01 '15 at 15:06

2 Answers2

4

First, you need to construct the string appropriately. You cannot construct it using the constructors that are looking for NULL terminators, which is what string(const char *) is looking for.

You have to use the constructor that takes a pointer and length.

string s("name\0first", 10);

If you have already constructed a string, and want to append data that has embedded NULLs, you can use the append() method.

string s;
s.append("name\0first", 10);
PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45
3

Use the constructor that takes the number of characters std::string s(buffer, nChars). It is the fifth from this reference.

Axel
  • 13,939
  • 5
  • 50
  • 79