Menu

cppcheck 2.13.0: FP invalidLifetime

2024-04-03
2024-04-03
  • Valentin Batz

    Valentin Batz - 2024-04-03

    The following code produces a false positive regarding the check [invalidLifetime]

    #include <iostream>
    #include <memory>
    #include <string>
    
    void log_format(const char *msg) {
      int size;
      int max;
      std::string str;
      {
        char buf[256];
        max = (int)sizeof(buf);
        size = snprintf(buf, sizeof(buf), "fmt %s", msg);
        if (size < 0) {
          std::cerr << "snprintf failed\n";
        } else if (size <= max) {
          str.assign(buf);
        }
      }
      if (size > max) {
        std::unique_ptr<char[]> buf(new char[size]);
    
        size = snprintf(buf.get(), std::size_t(size), "fmt %s", msg);
        if (size >= 0) {
          str.assign(buf.get());
        } else {
          std::cerr << "snprintf failed\n";
        }
      }
      std::cerr << str;
    }
    

    Error output from cppcheck 2.13.0:

    lifetime.cpp:29:16: error: Using object that points to local variable 'buf' that is out of scope. [invalidLifetime]
      std::cerr << str;
                   ^
    lifetime.cpp:24:25: note: Raw pointer to smart pointer created here.
          str.assign(buf.get());
                            ^
    lifetime.cpp:24:25: note: Added to container 'str'.
          str.assign(buf.get());
                            ^
    lifetime.cpp:20:29: note: Variable created here.
        std::unique_ptr<char[]> buf(new char[size]);
                                ^
    lifetime.cpp:29:16: note: Using object that points to local variable 'buf' that is out of scope.
      std::cerr << str;
    
     
  • CHR

    CHR - 2024-04-03

    Thanks for reporting, ticket is here: https://trac.cppcheck.net/ticket/12568

     
    👍
    1

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.