* Analyzer memory leak finding
@ 2020-07-16 18:53 Jeffrey Walton
0 siblings, 0 replies; only message in thread
From: Jeffrey Walton @ 2020-07-16 18:53 UTC (permalink / raw)
To: gcc-help
Hi Everyone,
I'm using GCC 10.1 on Fedora 32, x86_64, fully patched. I'm performing
some analyzer builds using -fanalyzer.
GCC is flagging a function as leaking memory, but it is not really.
The function is returning a malloc'd pointer, but the pointer is
aligned in the function. It may be a different pointer than the one
returned by malloc, but it is in the same malloc'd block.
The function and analyzer complaint is below.
How can I sidestep the finding in this case?
Thanks in advance.
========================================
void *
mmalloca (size_t n)
{
/* Allocate one more word, used to determine the address to pass to freea(),
and room for the alignment ≡ sa_alignment_max mod 2*sa_alignment_max. */
size_t nplus = n + sizeof (small_t) + 2 * sa_alignment_max - 1;
if (nplus >= n)
{
char *mem = (char *) malloc (nplus);
if (mem != NULL)
{
char *p =
(char *)((((uintptr_t)mem + sizeof (small_t) + sa_alignment_max - 1)
& ~(uintptr_t)(2 * sa_alignment_max - 1))
+ sa_alignment_max);
/* Here p >= mem + sizeof (small_t),
and p <= mem + sizeof (small_t) + 2 * sa_alignment_max - 1
hence p + n <= mem + nplus.
So, the memory range [p, p+n) lies in the allocated memory range
[mem, mem + nplus). */
((small_t *) p)[-1] = p - mem;
/* p ≡ sa_alignment_max mod 2*sa_alignment_max. */
return p;
}
}
/* Out of memory. */
return NULL;
}
========================================
malloca.c:76:11: warning: leak of ‘mem’ [CWE-401] [-Wanalyzer-malloc-leak]
76 | return p;
| ^~~~~~
‘mmalloca’: events 1-7
|
| 59 | if (nplus >= n)
| | ^
| | |
| | (1) following ‘true’ branch (when ‘n <= nplus’)...
| 60 | {
| 61 | char *mem = (char *) malloc (nplus);
| | ~~~~
| | |
| | (2) ...to here
| | (3) allocated here
| 62 |
| 63 | if (mem != NULL)
| | ~
| | |
| | (4) assuming ‘mem’ is non-NULL
| | (5) following ‘true’ branch (when ‘mem’ is non-NULL)...
| 64 | {
| 65 | char *p =
| | ~~~~
| | |
| | (6) ...to here
|......
| 76 | return p;
| | ~~~~~~
| | |
| | (7) ‘mem’ leaks here; was allocated at (3)
^ permalink raw reply [flat|nested] only message in thread
only message in thread, other threads:[~2020-07-16 18:54 UTC | newest]
Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2020-07-16 18:53 Analyzer memory leak finding Jeffrey Walton
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).