Menu

Issue with memory/resource leaks in if else clause

2021-02-17
2021-02-26
  • Rama Kunapuli

    Rama Kunapuli - 2021-02-17

    Hello;

    I submitted the following code to cppcheck.

    int main()
    {
    char p = malloc(10);
    int x = 10;
    if (x > 0 ) {
    char
    q = malloc(10);
    strcpy(q,"Hello");
    printf("\n %s",q);
    //free(q);
    }
    else {
    char *q1 = malloc(10);
    strcpy(q1,"Hello");
    printf("\n %s",q1);
    //free(q1);
    }
    return 0;
    }
    =================
    cppcheck 2.3 just shows memory leak of variable p but not of q or q1.
    possible bug?

    Best,
    RK

     
  • Daniel Marjamäki

    Thanks! Very strange. I can reproduce. I have created issue https://trac.cppcheck.net/ticket/10182

     
  • Rama Kunapuli

    Rama Kunapuli - 2021-02-17

    Thank you.

    Some additional information. Looks like if I add an extra if else loop so the code looks like below:

    int main()
    {
    char p = malloc(10);
    int x = 10;
    if (x > 0 ) {
    char
    q = malloc(10);
    strcpy(q,"Hello");
    printf("\n %s",q);
    //free(q);
    }
    else {
    char q1 = malloc(10);
    strcpy(q1,"Hello");
    printf("\n %s",q1);
    //free(q1);
    }
    if (x < 0 ) {
    char
    q = malloc(10);
    strcpy(q,"Hello");
    printf("\n %s",q);
    //free(q);
    }
    else {
    char *q1 = malloc(10);
    strcpy(q1,"Hello");
    printf("\n %s",q1);
    //free(q1);
    }

                return 0;
    

    }

    I see cppcheck shows memory leaks (correctly) for all three variables p,q,q1.

     
  • rikard

    rikard - 2021-02-26

    This is now fixed on the development branch of cppcheck and will be part of next release. For the first example, all three memory leaks will be reported and for the second, all five leaks will be reported, with the correct lines.

    Thanks for reporting!

     

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.