https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105530
Bug ID: 105530 Summary: Analyzer makes wrong conclusions for the malloc (deallocator, ptr-index) attribute Product: gcc Version: 11.3.1 Status: UNCONFIRMED Severity: normal Priority: P3 Component: analyzer Assignee: dmalcolm at gcc dot gnu.org Reporter: dilyan.palauzov at aegee dot org Target Milestone: --- gcc (GCC) 11.2.1 20220413 (compiled from git) For a.c: #include <stdlib.h> void fr(char* x) { free(x); } __attribute__((malloc, malloc(fr, 1))) char * al() { return (char*) malloc(10); } int main() { fr(al()); return 0; } $ gcc a.c -fanalyzer prints: a.c: In function ‘al’: a.c:8:10: warning: leak of ‘al()’ [CWE-401] [-Wanalyzer-malloc-leak] 8 | return (char*) malloc(10); | ^~~~~~~~~~~~~~~~~~ ‘main’: events 1-3 | | 11 | int main() { | | ^~~~ | | | | | (1) entry to ‘main’ | 12 | fr(al()); | | ~~~~~~~~ | | | | | (2) allocated here | | (3) calling ‘al’ from ‘main’ | +--> ‘al’: events 4-5 | | 7 | __attribute__((malloc, malloc(fr, 1))) char * al() { | | ^~ | | | | | (4) entry to ‘al’ | 8 | return (char*) malloc(10); | | ~~~~~~~~~~~~~~~~~~ | | | | | (5) ‘al()’ leaks here; was allocated at (2) | a.c: In function ‘main’: a.c:12:3: warning: ‘al()’ should have been deallocated with ‘free’ but was deallocated with ‘fr’ [CWE-762] [-Wanalyzer-mismatchi[4/1963] ocation] 12 | fr(al()); | ^~~~~~~~ ‘main’: events 1-2 | | 11 | int main() { | | ^~~~ | | | | | (1) entry to ‘main’ | 12 | fr(al()); | | ~~~~~~~~ | | | | | (2) calling ‘al’ from ‘main’ | +--> ‘al’: events 3-4 | | 7 | __attribute__((malloc, malloc(fr, 1))) char * al() { | | ^~ | | | | | (3) entry to ‘al’ | 8 | return (char*) malloc(10); | | ~~~~~~~~~~ | | | | | (4) allocated here (expects deallocation with ‘free’) | <------+ | ‘main’: events 5-6 | | 12 | fr(al()); | | ^~~~~~~~ | | | | | (5) returning to ‘main’ from ‘al’ | | (6) deallocated with ‘fr’ here; allocation at (4) expects deallocation with ‘free’ | Now, I do not understand these warnings. First of all, nothing is leaked. > a.c:12:3: warning: ‘al()’ should have been deallocated with ‘free’ but was > deallocated with ‘fr’ [CWE-762] [-Wanalyzer-mismatchi[4/1963] The complier/analyzer is explicitly told by the malloc(fr, 1) attribute, that fr() is the right way to deallocate the result of al(). > a.c:8:10: warning: leak of ‘al()’ [CWE-401] [-Wanalyzer-malloc-leak] return (char*) malloc(10); is by itself not a memory leak.