https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94458
Bug ID: 94458 Summary: -Wanalyzer-malloc-leak false positive when returning a heap-allocated struct by value holding a heap-allocated pointer Product: gcc Version: unknown Status: UNCONFIRMED Severity: normal Priority: P3 Component: analyzer Assignee: dmalcolm at gcc dot gnu.org Reporter: simon.marchi at polymtl dot ca Target Milestone: --- Variation of [1], where the returned struct is heap-allocated, rather than returned by value. [1] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94378 Source: #include <stdlib.h> struct ret { int **array; }; struct ret *allocate_stuff(void) { struct ret *ret; ret = calloc(1, sizeof (struct ret)); if (!ret) { abort(); } ret->array = calloc (10, sizeof(int *)); if (!ret->array) { abort(); } return ret; } Analyzer report: $ /opt/gcc/git/bin/gcc a.c -g3 -O0 -fanalyzer -c -Wall -Werror a.c: In function ‘allocate_stuff’: a.c:18:10: error: leak of ‘<unknown>’ [CWE-401] [-Werror=analyzer-malloc-leak] 18 | if (!ret->array) { | ~~~^~~~~~~ ‘allocate_stuff’: events 1-7 | | 13 | if (!ret) { | | ^ | | | | | (1) following ‘false’ branch (when ‘ret’ is non-NULL)... |...... | 17 | ret->array = calloc (10, sizeof(int *)); | | ~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | | | (2) ...to here | | (3) allocated here | 18 | if (!ret->array) { | | ~ ~~~~~~~~~~ | | | | | | | (7) ‘<unknown>’ leaks here; was allocated at (3) | | (4) assuming ‘<unknown>’ is non-NULL | | (5) following ‘false’ branch... |...... | 22 | return ret; | | ~~~ | | | | | (6) ...to here | cc1: all warnings being treated as errors $ /opt/gcc/git/bin/gcc --version gcc (GCC) 10.0.1 20200401 (experimental) The analyzer says the memory allocated at (3) is leaked, but it is in fact pointed by the returned struct.