Menu

Can Cppcheck Detect Smart Pointer Bugs in C++, such as Null Dereference or Use-After-Move?

2025-08-04
2025-08-04
  • Mingxiu Wang

    Mingxiu Wang - 2025-08-04

    I’m investigating memory-related issues involving C++ smart pointers (std::unique_ptr, std::shared_ptr) and would like to know if Cppcheck is capable of detecting bugs such as:

    Null dereference

    Use-after-move

    Double deletion or invalid memory access through smart pointers

    Does Cppcheck support detection of these patterns? If so, are there specific flags, configuration options, or coding practices that help Cppcheck better identify such issues? Sample code or documentation references would be very helpful.

     
  • CHR

    CHR - 2025-08-04

    Nullptr dereference has some issues: https://trac.cppcheck.net/ticket/12868
    This is detected though:

    void f(std::shared_ptr<int> p) {
        if (p)
            return;
        *p = 0;
    }
    

    Use-after-move should be detected with --enable=warning.

    Double deletion or invalid memory access is probably not implemented. This is not detected:

    void f(std::shared_ptr<int> p) {
        delete p.get();
        delete p.get();
    }
    
     

    Last edit: CHR 7 days ago

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.