Menu

danglingTemporaryLifetime false positive

Cyphall
2025-07-12
2025-07-14
  • Cyphall

    Cyphall - 2025-07-12

    It seems that saving the address of an element when iterating on a temporary std::span triggers this error.

    Sample code:

    #include <span>
    #include <vector>
    
    std::span<const int> getSpan(const std::vector<int>& vec)
    {
        return vec;
    }
    
    int main()
    {
        std::vector<int> values = {0, 1, 2, 3, 4};
    
        const int* selectedValue = nullptr;
        for (const int& value : getSpan(values))
        {
            if (value == 2)
            {
                selectedValue = &value;
                break;
            }
        }
    
        return selectedValue ? *selectedValue : 0;
    }
    

    Here, the std::span is temporary in the scope of the for loop, but not the objects it points to.

    cppcheck error (file paths were removed):

    error: Using pointer that is a temporary. [danglingTemporaryLifetime]
     return selectedValue ? *selectedValue : 0;
            ^
    note: Assigned to reference.
     for (const int& value : getSpan(values))
                     ^
    note: Address of variable taken here.
       selectedValue = &value;
                       ^
    note: Temporary created here.
     for (const int& value : getSpan(values))
                                    ^
    note: Using pointer that is a temporary.
     return selectedValue ? *selectedValue : 0;
            ^
    
     

    Last edit: Cyphall 2025-07-12
  • CHR

    CHR - 2025-07-14

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

     

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.