Menu

False positive memory leak when allocated in switch / case

2018-04-24
2021-01-29
  • Steve Grubb

    Steve Grubb - 2018-04-24

    Hello,

    I have run across a false positive and have created a minimal reproducer. If I assign a string member of a struct inside a switch / case but return on default, it thinks there is a leak on the default path.

    typedef struct s {
            char *str;
    } attr_t;
    
    attr_t *function(int type)
    {
            attr_t subj;
    
            switch(type)
            {
                    case NAME:
                            subj.str = strdup("?");
                            break;
                    default:
                            return NULL;
            }
            return subject_add(&sub);
    }
    

    Which is tested thusly:

    cppcheck --library=posix break.c
    [break.c:15]: (error) Memory leak: subj.str

    Line 15 is the return NULL. I have tested this on 1.80, 1.83, and current git. They all report the same thing. The leak is only reported when the posix library is used. This is where it picks up that strdup is an allocator.

     
  • CHR

    CHR - 2021-01-27

    This reproduces with v2.3 even without --library=posix.

     
  • CHR

    CHR - 2021-01-29
     

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.