Menu

knownConditionTrueFalse false positive

2025-02-28
2025-03-01
  • Nikita Leontiev

    Nikita Leontiev - 2025-02-28

    cppcheck 2.17.1 generates knownConditionTrueFalse false positive for double-checked locking singleton realization:

    #include <mutex>
    
    class ScopedLock
    {
    private:
        std::mutex *m_lock;
    public:
        explicit ScopedLock(std::mutex *lock) : m_lock(lock)
        {
            m_lock -> lock();
        }
        ~ScopedLock()
        {
            m_lock -> unlock();
        }
    };
    
    class Singleton
    {
    private:
        static Singleton *m_instance;
        static std::mutex m_lock;
    public:
        static Singleton *get_instance()
        {
            if (!m_instance)
            {
                ScopedLock lock(&m_lock);
                if (!m_instance)
                    m_instance = new Singleton();
            }
            return m_instance;
        }
        static void free_instance()
        {
            if (m_instance)
            {
                delete m_instance;
                m_instance = 0;
            }
        }
    };
    
    Singleton *Singleton::m_instance = 0;
    std::mutex Singleton::m_lock;
    
    test\main.cpp:29:8: style: Condition '!m_instance' is always true [knownConditionTrueFalse]
       if (!m_instance)
           ^
    test\main.cpp:26:7: note: Assuming that condition '!m_instance' is not redundant
      if (!m_instance)
          ^
    test\main.cpp:29:8: note: Condition '!m_instance' is always true
       if (!m_instance)
           ^
    
     
  • CHR

    CHR - 2025-02-28

    cppcheck does not consider multi-threaded execution.

     
  • Nikita Leontiev

    Nikita Leontiev - 2025-02-28

    cppcheck behavior is inconsistent, because it doesn't generate same warning for the code below:

    #include <mutex>
    
    class Singleton
    {
    private:
        static Singleton *m_instance;
        static std::mutex m_lock;
    public:
        static Singleton *get_instance()
        {
            if (!m_instance)
            {
                m_lock.lock();
                if (!m_instance)
                    m_instance = new Singleton();
                m_lock.unlock();
            }
            return m_instance;
        }
        static void free_instance()
        {
            if (m_instance)
            {
                delete m_instance;
                m_instance = 0;
            }
        }
    };
    
    Singleton *Singleton::m_instance = 0;
    std::mutex Singleton::m_lock;
    
     
  • CHR

    CHR - 2025-03-01

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

     

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.