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; }
I can reproduce with v2.3.
I have created a ticket here: https://trac.cppcheck.net/ticket/10158
Log in to post a comment.
Put the code posted at the bottom into file a file called runme.c and run cppcheck:
The memory leak is a false positive unless WORKAROUND is defined. The workaround requires an extra temporary variable, which is odd!
I can reproduce with v2.3.
I have created a ticket here: https://trac.cppcheck.net/ticket/10158