Home > Back-end >  Append a null terminator to a C string
Append a null terminator to a C string

Time:11-08

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?

CodePudding user response:

The append overload you're using accepts a C string, which is null-terminated (that is: the first null-byte marks its end).

The easiest way here is probably to use a different overload of append:

  s.append(fill - len, '\0');

Note that this requires C 20. For older C standards, there's

   s.resize(fill, '\0');

or just

   s.resize(fill);

Come to think of it, this may be a clearer way to describe what you're doing, anyway. I like the second option here for clarity.

  • Related