Analyzer memory leak finding

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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)




[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux