Menu

False positive memory leak unless there is named return variable

2018-10-15
2021-01-30
  • William Fulton

    William Fulton - 2018-10-15

    Put the code posted at the bottom into file a file called runme.c and run cppcheck:

    $ cppcheck runme.c 
    Checking runme.c...
    [runme.c:30]: (error) Memory leak: s.str
    Checking runme.c: WORKAROUND...
    $ 
    

    The memory leak is a false positive unless WORKAROUND is defined. The workaround requires an extra temporary variable, which is odd!

    // file runme.c
    #include <string.h>
    #include <stdlib.h>
    #include <stdio.h>
    
    typedef struct String {
      char *str;
    } String;
    
    typedef struct Object {
      String *data;
    } Object;
    
    Object * NewObject(String *s) {
      Object *obj = malloc(sizeof(Object));
      obj->data = s;
      return obj;
    }
    
    Object * NewString(const char *str) {
      String *s = malloc(sizeof(String));
      s->str = malloc(strlen(str) + 1);
      strcpy(s->str, str);
    #if defined(WORKAROUND)
      {
        Object *obj = NewObject(s);
        return obj;
      }
    #else
      return NewObject(s);
    #endif
    }
    
    void DeleteObject(Object *o) {
      Object *obj = (Object *)o;
      String *s = (String *)obj->data;
      free(s->str);
      free(s);
      free(obj);
    };
    
    int main() {
      Object *obj = NewString("hello there");
      printf("%s\n", obj->data->str);
      DeleteObject(obj);
      return 0;
    }
    
     
  • CHR

    CHR - 2021-01-26

    I can reproduce with v2.3.

     
  • CHR

    CHR - 2021-01-30

    I have created a ticket here: https://trac.cppcheck.net/ticket/10158

     

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.