https://gcc.gnu.org/bugzilla/show_bug.cgi?id=117940

            Bug ID: 117940
           Summary: False positive -Wanalyzer-malloc-leak on NULL return
                    value
           Product: gcc
           Version: 14.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: theholgi at posteo dot de
  Target Milestone: ---

This sample code is a simplified excerpt from mbedTLS asn1parse.c:
-----
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>

struct list_t;

typedef struct list_t {
  int item;
  struct list_t* next;
} list_t;

typedef struct {
  list_t* cur;
} context_t;

bool list_add(void* ctx, int item)
{
  context_t* cb_ctx = ctx;
  list_t* cur = cb_ctx->cur;
  cur->next = malloc(sizeof(list_t));
  if (cur->next == NULL)
  {
    return false;
  } else
  {
    cur = cur->next;
    cur->item = item;
  }
  cb_ctx->cur = cur;
  return true;
}
-----
$ cc -c -o pointer_leak.o pointer_leak.c -fanalyzer
pointer_leak.c: In function ‘list_add’:
pointer_leak.c:21:10: warning: leak of ‘*cur.next’ [CWE-401]
[-Wanalyzer-malloc-leak]
   21 |   if (cur->next == NULL)
      |       ~~~^~~~~~
  ‘list_add’: events 1-2
    |
    |   20 |   cur->next = malloc(sizeof(list_t));
    |      |               ^~~~~~~~~~~~~~~~~~~~~~
    |      |               |
    |      |               (1) allocated here
    |   21 |   if (cur->next == NULL)
    |      |       ~~~~~~~~~
    |      |          |
    |      |          (2) ‘*cur.next’ leaks here; was allocated at (1)
    |
-----
It is of course not possible to leak a failed allocation NULL pointer.
It is essential that the context is casted from a void*; when the function gets
a context_t* the problem disappears.

Tested with:
$ cc --version | head -n1
cc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
$ gcc-14 --version | head -n1
gcc (GCC) 14.2.0

Reply via email to