Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i embed NULL character inside string in C++?

Tags:

c++

string

null

Can i use string in C++ which support embedded NULL character?

My issue is: Constructing string with embedded NULL and hence sent it to C++ DLL as an array of bytes.

    string inputStr("he\0llo", 6);
    int byteLength = 6;
    BYTE *inputByte = (BYTE*)(char*)inputStr.c_str();
    ApplyArabicMapping(inputByte , byteLength);
like image 206
Ahmed Mostafa Avatar asked Feb 28 '26 13:02

Ahmed Mostafa


2 Answers

Yes, std::string supports storing NULL characters because it is not NULL-terminated. You can create one in many ways:

string str("he\0llo", 6);
str.append(1, '\0');
str.push_back('\0');
const char[] cstr = "hell\0o";
string str2(cstr, cstr + sizeof(cstr) - 1); // - 1 for the NULL
like image 106
Seth Carnegie Avatar answered Mar 03 '26 03:03

Seth Carnegie


You can use counted strings, where the character buffer is stored alongside with its "content length"; this allows you to embed any character. std::string, for example, is a kind of counted string.

Obviously, you cannot pass such a string to a function that expects a classic C-string, because it will see the first null it encounters as the string terminator.

like image 23
Matteo Italia Avatar answered Mar 03 '26 02:03

Matteo Italia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!