https://gcc.gnu.org/bugzilla/show_bug.cgi?id=127593
Bug ID: 127593
Summary: Analyzer reports memory leak for valid code
(-Wanalyzer-malloc-leak)
Product: gcc
Version: 17.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: analyzer
Assignee: dmalcolm at gcc dot gnu.org
Reporter: b.buschinski at googlemail dot com
Target Milestone: ---
For the following code:
Compiler explorer: https://godbolt.org/z/vxnWP8vrx
```
#include <stdlib.h>
#include <stddef.h>
struct public_stuff {
void * data;
};
struct internal_stuff {
int bar;
struct public_stuff pub;
int foo;
};
struct public_stuff * create_public()
{
struct internal_stuff * internal = malloc(sizeof(struct internal_stuff));
internal->pub.data = NULL;
return &internal->pub;
}
void free_public(struct public_stuff * pubs)
{
struct internal_stuff * internal = (struct internal_stuff *)((unsigned
char*)pubs - offsetof(struct internal_stuff, pub));
free(internal);
}
```
when I compile it with -fanalyzer, it reports:
```
<source>: In function 'create_public':
<source>:18:12: warning: leak of 'internal' [CWE-401] [-Wanalyzer-malloc-leak]
18 | return &internal->pub;
| ^~~~~~~~~~~~~~
'create_public': events 1-2
|
| 16 | struct internal_stuff * internal = malloc(sizeof(struct
internal_stuff));
| | ^~~~~~
| | |
| | (1) allocated here
| 17 | internal->pub.data = NULL;
| 18 | return &internal->pub;
| | ~~~~~~~~~~~~~~
| | |
| | (2) 'internal' leaks here; was allocated at (1)
|
```
It reports a leak, but the `free_public` is able to fully free the allocated
memory without an issue.
See compiler explorer with ASAN and execution: https://godbolt.org/z/MYzebxMjf
So I wonder if this is a deficiency in the analyzer? Can the warnings be
somehow worked around?
Btw: In the compiler explorer this happens to all GCC versions that support the
analyzer, from 10 to the current git master.