https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102308
Bug ID: 102308 Summary: False positive -Wanalyzer-malloc-leak when writing to array in struct Product: gcc Version: 11.1.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: analyzer Assignee: dmalcolm at gcc dot gnu.org Reporter: matti.niemenmaa+gccbugs at iki dot fi Target Milestone: --- The following code: $ cat bug.c #include <stdlib.h> struct s { char *p; int arr[2]; }; int main(void) { struct s *s = malloc(sizeof *s); if (s) { s->p = malloc(1); for (int i = 0; i < 2; i++) s->arr[i] = -1; } if (s) { free(s->p); free(s); } } Triggers -Wanalyzer-malloc-leak of "<unknown>" (apparently the malloc(1)) in the loop that writes to the array: $ gcc --version | head -1 gcc (GCC) 11.1.0 $ gcc -fanalyzer -O2 -c -o /dev/null bug.c bug.c: In function ‘main’: bug.c:11:17: warning: leak of ‘<unknown>’ [CWE-401] [-Wanalyzer-malloc-leak] 11 | s->arr[i] = -1; | ~~~~~~~~~~^~~~ ‘main’: events 1-8 | | 8 | if (s) { | | ^ | | | | | (1) following ‘true’ branch (when ‘s’ is non-NULL)... | 9 | s->p = malloc(1); | | ~~~~~~~~~ | | | | | (2) ...to here | | (3) allocated here | 10 | for (int i = 0; i < 2; i++) | | ~~~~~ | | | | | (4) following ‘true’ branch (when ‘i != 2’)... | | (6) following ‘true’ branch (when ‘i != 2’)... | 11 | s->arr[i] = -1; | | ~~~~~~~~~~~~~~ | | | | | (5) ...to here | | (7) ...to here | | (8) ‘<unknown>’ leaks here; was allocated at (3) Even though there's evidently no leak. As shown, the above triggers even on -O2. With -O0 the example can be simplified a bit: #include <stdlib.h> struct s { char *p; int arr[1]; }; int main(void) { struct s s; s.p = malloc(1); for (int i = 0; i < 1; i++) s.arr[i] = -1; free(s.p); } Here the same type of leak is reported on -O0, but not -O2.