Menu

FP deallocuse in the while loop

mondaylord
2024-04-30
2024-05-10
  • mondaylord

    mondaylord - 2024-04-30

    I found if the dealloc use is in a while loop, then cppcheck won't warn this.
    Here is a sample file test.cpp

    int do_something()
    {
        while(1){
            int* p=new int[1];
            delete[] p;
            cout<<p[0];
            return 0;
        }
    }
    
    void foo() {
        int *nc = new int[10];
        delete[] nc;
        cout<<nc[0];
    }
    
    int main(int argc, char* argv[])
    {
        return 0;
    }
    

    And cppcheck(commit e2fa3cb10932d6eaa1a228cbfa6822e18500a922) has no warning of cout<<p[0]

    Checking test.cpp ...
    test.cpp:14:11: error: Dereferencing 'nc' after it is deallocated / released [deallocuse]
        cout<<nc[0];
              ^
    test.cpp:5:12: error: Memory is allocated but not initialized: p [uninitdata]
      delete[] p;
               ^
    test.cpp:13:14: error: Memory is allocated but not initialized: nc [uninitdata]
        delete[] nc;
    
     
    • mondaylord

      mondaylord - 2024-05-06

      @danielmarjamaki Could you take a look at this question :)

       
  • CHR

    CHR - 2024-05-06
     
    • mondaylord

      mondaylord - 2024-05-10

      Can we just add a check in lib/checkleakautovar.cpp:646 to handle loops like this?

          else if (Token::Match(tok, "for|while|do")) {
              continue;
          }
      
          // unknown control.. (TODO: handle loops)
          else if ((Token::Match(tok, "%type% (") && Token::simpleMatch(tok->linkAt(1), ") {")) || Token::simpleMatch(tok, "do {")) {
              varInfo.clear();
              return false;
          }
      
       
  • CHR

    CHR - 2024-05-10
     

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.