In order to implement a client to some protocol that expects null-byte padding to a specific string, I implemented a functions that pads a string with a specific amount of null bytes:
string padToFill(string s, int fill){
int len = s.length();
if (len < fill){
for (int i = 0; i < fill - len; i++){
s.append("\0");
}
}
return s;
}
However, in practice, the result I am getting from this function is identical to the string I am getting as argument. So for example padToFill("foo", 5) is foo and not foo\0\0. Even tho c++ strings are expected to handle null bytes as any other character.
How do I achieve the desired null padding?
std::stringcan have many\0at the end, but there are some pitfalls that could lead you to believe that there are none. The code you posted looks ok. What is the code you used to see how many null terminators are in the result?s.push_back('\0');Note thatstd::stringalready manages a\0-terminator at the end of the string, which is not part of the length. If you push back additional\0-terminators, those will be part of the length (and there will still be the additional not counted\0-terminated caboose).