http://gcc.gnu.org/bugzilla/show_bug.cgi?id=58237
Bug ID: 58237 Summary: gcc fails to detect obvious resource leaks Product: gcc Version: 4.9.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c Assignee: unassigned at gcc dot gnu.org Reporter: dcb314 at hotmail dot com Some code has obvious resource leaks # include <stdio.h> void f1(const char *str) { FILE * fp = fopen(str, "r"); char buf[10]; while (fgets(buf, 10, fp) != NULL) { /* Do something with buf */ } /* Missing call to fclose. Need warning here for resource leak */ } It would be nice if gcc could notice the obvious missing call to fclose and produce a warning about a resource leak. To help some test driven development, here are some additional test cases. This case is slightly more subtle, but still a warning would be nice for when flag == 0. void f2(const char *str, int flag) { FILE * fp = fopen(str, "r"); char buf[10]; while (fgets(buf, 10, fp) != NULL) { /* Do something with buf */ } /* fclose only sometimes called. * Still a leak for the case when flag == 0. */ if (flag) fclose(fp); } For this one, all bets are off since we don't know what function f31() does with fp. extern void f31( FILE * fp); void f3(const char *str) { FILE * fp = fopen(str, "r"); char buf[10]; while (fgets(buf, 10, fp) != NULL) { /* Do something with buf */ } /* Not sure if fclose executed by f31 or not. Say nothing */ f31(fp); } Here is the obvious case where we shouldn't say anything void f4(const char *str) { FILE * fp = fopen(str, "r"); char buf[10]; while (fgets(buf, 10, fp) != NULL) { /* Do something with buf */ } /* Nothing to say here. */ fclose(fp); } And here is another one where producing a warning message seems counter - productive. void main(int argc, const char * argv[]) { FILE * fp = fopen(argv[0], "r"); char buf[10]; while (fgets(buf, 10, fp) != NULL) { /* Do something with buf */ } /* Nothing to say here, because we are in main. */ } Of course, there are many other matched pairs of functions (open, close), (opendir, closedir) etc that could also have resource leak warnings. A useful first step would be to pick one pair and implement for that. Then extend to other pairs. Here is cppcheck doing what I want $ ~/cppcheck/cppcheck/cppcheck aug24a.cc Checking aug24a.cc... [aug24a.cc:16]: (error) Resource leak: fp [aug24a.cc:32]: (error) Resource leak: fp $