Menu

false negative: auto-variable assigned to a function parameter

2020-08-08
2020-08-10
  • houzhengtao

    houzhengtao - 2020-08-08
    typedef struct {
        int *a;
    } testStru;
    
    void AssignLocalVarAddressToOutsideVar_1(testStru *myStru, int **n)
    {
        int b = 1;
        myStru->a = &b;  //scene1
        *n = &b;
    }
    
    
    typedef struct {
        testStru m;
    } testStru2;
    
    void AssignLocalVarAddressToOutsideVar_2(testStru2 *myStru2)
    {
        int b = 1;
        myStru2->m.a = &b;  //scene2
    }
    
    
    typedef struct {
        testStru2 m;
    } testStru3;
    
    void AssignLocalVarAddressToOutsideVar_3(testStru3 *myStru3)
    {
        int b = 1;
        myStru3->m.m.a = &b;  //scene3
    }
    
    
    typedef struct {
        testStru3 m;
    } testStru4;
    
    void AssignLocalVarAddressToOutsideVar_4(testStru4 *myStru4)
    {
        int b = 1;
        myStru4->m.m.m.a = &b;  //scene4
    }
    
    
    int main()
    {
        testStru myStru = {0};
        int *n = 0;
        AssignLocalVarAddressToOutsideVar_1(&myStru, &n);
    
        testStru2 myStru2 = {0};
        AssignLocalVarAddressToOutsideVar_2(&myStru2);
    
        testStru3 myStru3 = {0};
        AssignLocalVarAddressToOutsideVar_3(&myStru3);
    
        testStru4 myStru4 = {0};
        AssignLocalVarAddressToOutsideVar_4(&myStru4);
    
        return 0;
    }
    

    In scene1, cppcheck reports an error : Address of local auto-variable assigned to a function parameter. [autoVariables].
    In scene2, 3, 4, cppcheck reports no error.
    From source code, I found you use exhaustive attack method to detect such problem. Is there a better method ?

     
  • Daniel Marjamäki

    Thanks! I created ticket https://trac.cppcheck.net/ticket/9831

    From source code, I found you use exhaustive attack method to detect such problem. Is there a better method ?

    I have the feeling that this check is ~10 years old. So it's likely that it can be refactored and made more effective.

    I don't remember off the top of my head exactly how this checker works. But checking for the assignment itself should be done using the AST/SymbolDatabase. Then checking that the address does not "leak" could be checked by FwdAnalysis... if something can be added in FwdAnalysis that replaces CheckLeakAutoVar and CheckMemoryLeak that would be pretty cool.

     

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.