0

Here is the typical (pseudo) code I wish to handle in clang-tidy (eg also here) for conveying an optionally null terminated fixed size buffer to std::string:

% cat str.cc
#include <iostream>
#include <string>

// read byte buffer from file, at most 4 bytes read:
static void read_buf4(char buf[4])
{
  buf[0] = 'A';
  buf[1] = 'B';
  buf[2] = 'C';
  // buf[3] = 'D';
  buf[3] = 0;
}

int main()
{
  char buf[4];
  read_buf4(buf);
  std::string owner = std::string(buf,sizeof buf).c_str();
  // I want owner.size() to return strnlen(buf,4):
  std::cout << owner << "/" << owner.size() << std::endl;
  return 0;
}

What would be the most acceptable solution to help clang-tidy understand the code ?

Currently reporting:

% clang-tidy --checks="-*,readability-redundant-string-cstr" str.cc
Error while trying to load a compilation database:
Could not auto-detect compilation database for file "str.cc"
No compilation database found in /tmp or any parent directory
fixed-compilation-database: Error while opening fixed database: No such file or directory
json-compilation-database: Error while opening JSON database: No such file or directory
Running without flags.
1 warning generated.
/tmp/str.cc:17:23: warning: redundant call to 'c_str' [readability-redundant-string-cstr]
  std::string owner = std::string(buf,sizeof buf).c_str();
                      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                      std::string(buf,sizeof buf)
malat
  • 12,152
  • 13
  • 89
  • 158
  • 3
    Just remove the call to `c_str`? Is there a reason you're doing that? – Alan Birtles May 02 '23 at 09:34
  • 2
    Whatever you're hoping adding `c_str` to achieve it isn't doing that. It's redundant (hence the warning) at most it's just a less efficient way of copying the string – Alan Birtles May 02 '23 at 09:38
  • Why not simply construct the string as `std::string(buf, strnlen(buf, 4))` (or, alternatively, call `owner.resize(strnlen(buf, 4))` after construction)? That would convey intent to the reader in a much more obvious way. – You May 02 '23 at 09:56
  • Ah, I hadn't spotted the null in your buffer, I've edited your question to clarify what you're trying to do – Alan Birtles May 02 '23 at 10:10

0 Answers0