https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94365
Bug ID: 94365 Summary: false positive leak when using container_of-like constructs Product: gcc Version: 10.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: analyzer Assignee: dmalcolm at gcc dot gnu.org Reporter: npfhrotynz-ptnqh.myvf at noclue dot notk.org Target Milestone: --- Created attachment 48136 --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=48136&action=edit test program.c First, thanks for this awesome feature! I'm not sure how "ready" it is, but there are other open bugs and I did not see this one, so here goes... I'm often using patterns where I return a pointer to an inner field of a struct and then use it with container_of later on. The attached example program gives two warnings; only the first one is interesting to me but figured I could cite both since I stumbled on the second when writing the reproducer... ----------------------------------------------------------------------------- In function ‘foo’: t.c:22:9: warning: leak of ‘a’ [CWE-401] [-Wanalyzer-malloc-leak] 22 | return &a->b; | ^~~~~ ‘foo’: events 1-5 | | 14 | struct container *a = malloc(sizeof(*a)); | | ^~~~~~~~~~~~~~~~~~ | | | | | (1) allocated here |...... | 19 | if (!a) | | ~ | | | | | (2) assuming ‘a’ is non-NULL | | (3) following ‘false’ branch (when ‘a’ is non-NULL)... |...... | 22 | return &a->b; | | ~~~~~ | | | | | (4) ...to here | | (5) ‘a’ leaks here; was allocated at (1) | ----------------------------------------------------------------------------- In function ‘main’: t.c:41:2: warning: ‘free’ of ‘<unknown>’ which points to memory not on the heap [CWE-590] [-Wanalyzer-free-of-non-heap] 41 | free(container_of(b, struct container, b)); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ‘main’: events 1-2 | | 29 | int main() { | | ^~~~ | | | | | (1) entry to ‘main’ | 30 | struct a_struct *b = foo(); | | ~~~~~ | | | | | (2) calling ‘foo’ from ‘main’ | +--> ‘foo’: events 3-5 | | 13 | struct a_struct *foo() { | | ^~~ | | | | | (3) entry to ‘foo’ |...... | 19 | if (!a) | | ~ | | | | | (4) following ‘false’ branch (when ‘a’ is non-NULL)... |...... | 22 | return &a->b; | | ~~~~~ | | | | | (5) ...to here | <------+ | ‘main’: events 6-10 | | 30 | struct a_struct *b = foo(); | | ^~~~~ | | | | | (6) returning to ‘main’ from ‘foo’ |...... | 33 | if (!b) | | ~ | | | | | (7) following ‘false’ branch (when ‘b’ is non-NULL)... |...... | 41 | free(container_of(b, struct container, b)); | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | | | (8) ...to here | | (9) pointer is from here | | (10) call to ‘free’ here | ----------------------------------------------------------------------------- I would think that as long as it is programmatically possible to go back to the allocated pointer (e.g. the return value is a constant offset from malloc value) then there should be no leak. Thanks, -- Dominique Martinet