reddy - 2020-10-19

Hi, I am scaning the following code with cppcheck, it seems cppcheck can not detect memory leak in switch case sentences, and its following codes.
If I delete the switch case code, it will detect all leaks.
I've tested on the latest github release and cppcheck2.0.

////////My test code://///////////////
void func()
{
    char *test = (char *)nwy_malloc(100); //leak can be detected
}

int func2()
{
    switch(x) {
        case 1:
            break;
        case 2:
        {
            int a;
            break;
        }
        case 3:
            char *p = malloc(100); **//leak can not be detected**
            memset(p, 0, 100);
            break;
        default:
            break;
    }
    char *p1 = malloc(100); **//leak can not be detected if prev switch exist**
    memset(p1, 0, 100);
    char *p2 = (char *)nwy_malloc(100); **//leak can not be detected if prev switch exist**
    memset(p2, 0, 100);
    char *p3 = nwy_modem_mem_alloc(100, 20); **//leak can not be detected if prev switch exist**
    memset(p3, 0, 100);
    char *p4 = nwy_modem_mem_alloc(100);
    memset(p4, 0, 100);

    return 0;
}

///////////////////////////////////command/////////////////////////////////////////
cppcheck$ ./cppcheck.new -q --enable=all --library=nwy.cfg test.c
test.c:6:1: error: Memory leak: test [memleak]
}
^
test.c:5:13: style: Variable 'test' is assigned a value that is never used. [unreadVariable]
char test = (char )nwy_malloc(100);
^
test.c:16:7: style: Unused variable: a [unusedVariable]
int a;
^
test.c:3:0: style: The function 'func' is never used. [unusedFunction]

^

my config file:<nwy.cfg></nwy.cfg>

<def format="2">
<!--
  <define name="nwy_malloc" value="nwy_modem_mem_alloc"/>
  <define name="nwy_free" value="nwy_modem_mem_free"/>
-->
  <function name="nwy_modem_mem_alloc">
    <use-retval/>
    <returnValue type="void *"/>
    <noreturn>false</noreturn>
    <arg nr="1" direction="in">
      <not-uninit/>
      <valid>0:</valid>
    </arg>
    <arg nr="2" direction="in"/>
  </function>
  <function name="nwy_modem_mem_free">
    <noreturn>false</noreturn>
    <returnValue type="void"/>
    <arg nr="1">
      <not-uninit/>
    </arg>
    <arg nr="2" direction="in"/>
  </function>
  <function name="nwy_malloc">
    <use-retval/>
    <returnValue type="void *"/>
    <noreturn>false</noreturn>
    <arg nr="1" direction="in">
      <not-uninit/>
      <valid>0:</valid>
    </arg>
  </function>
  <function name="nwy_free">
    <noreturn>false</noreturn>
    <returnValue type="void"/>
    <arg nr="1">
      <not-uninit/>
    </arg>
  </function>
 <memory>
 <alloc>nwy_modem_mem_alloc</alloc>
 <dealloc>nwy_modem_mem_free</dealloc>
 <alloc>nwy_malloc</alloc>
 <dealloc>nwy_free</dealloc>
 </memory>
</def>
 

Last edit: reddy 2020-10-22