Menu

cppcheck should report enneficient std::strlen(str.c_str()) -> str.size()

2019-03-02
2019-03-04
  • Dominique Pelle

    Dominique Pelle - 2019-03-02

    Consider the following c++ code:

    #include <cstring>
    #include <iostream>
    #include <string>
    
    int main()
    {
      std::string s = "foo";
    
      // std::strlen(s.c_str(()) is inefficient and should rather
      // be written as s.size().
      std::cout << std::strlen(s.c_str()) << std::endl;
      return 0;
    }
    

    Neither gcc -Wall, nor clang -Wall, nor cppcheck warn about
    the inneficient std::strlen(s.c_str()) which should rather
    be s.size().

    It may seem silly to write such inneficient code, but it can happen
    by accident when refactoring code replacing C string with std::string.
    It would be nice if cppcheck could warn about it.

     
  • Daniel Marjamäki

    sounds good to me. I created https://trac.cppcheck.net/ticket/9015

    If you want.. feel free to work on this.

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.