https://gcc.gnu.org/bugzilla/show_bug.cgi?id=104979
Bug ID: 104979
Summary: False positive from -Wanalyzer-malloc-leak with cast
within boxed pointer
Product: gcc
Version: 12.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: analyzer
Assignee: dmalcolm at gcc dot gnu.org
Reporter: dmalcolm at gcc dot gnu.org
Target Milestone: ---
Given:
#include <stdlib.h>
typedef struct boxed_ptr { void *value; } boxed_ptr;
boxed_ptr
boxed_malloc (size_t sz)
{
boxed_ptr result;
result.value = malloc (sz);
return result;
}
boxed_ptr
boxed_free (boxed_ptr ptr)
{
free (ptr.value);
}
const boxed_ptr boxed_null = {NULL};
struct link
{
boxed_ptr m_ptr;
};
boxed_ptr test_29 (void)
{
boxed_ptr res = boxed_malloc (sizeof (struct link));
if (!res.value)
return boxed_null;
((struct link *)res.value)->m_ptr = boxed_malloc (sizeof (struct link));
return res;
}
-fanalyzer emits (incorrectly, I think):
<source>: In function 'boxed_malloc':
<source>:10:10: warning: leak of '<return-value>.value' [CWE-401]
[-Wanalyzer-malloc-leak]
10 | return result;
| ^~~~~~
'test_29': events 1-4
|
| 26 | boxed_ptr test_29 (void)
| | ^~~~~~~
| | |
| | (1) entry to 'test_29'
|......
| 29 | if (!res.value)
| | ~
| | |
| | (2) following 'false' branch...
| 30 | return boxed_null;
| 31 | ((struct link *)res.value)->m_ptr = boxed_malloc (sizeof (struct
link));
| | ~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | | |
| | | (4) calling 'boxed_malloc'
from 'test_29'
| | (3) ...to here
|
+--> 'boxed_malloc': events 5-7
|
| 6 | boxed_malloc (size_t sz)
| | ^~~~~~~~~~~~
| | |
| | (5) entry to 'boxed_malloc'
|......
| 9 | result.value = malloc (sz);
| | ~~~~~~~~~~~
| | |
| | (6) allocated here
| 10 | return result;
| | ~~~~~~
| | |
| | (7) '<return-value>.value' leaks here; was
allocated at (6)
|
https://godbolt.org/z/1e9n8dnvM