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

            Bug ID: 104269
           Summary: Bogus -Wuse-after-free seen in xen
           Product: gcc
           Version: 12.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: marxin at gcc dot gnu.org
                CC: msebor at gcc dot gnu.org
  Target Milestone: ---

Reduced from xen package:

$ cat core.c
#include <stdlib.h>

typedef struct xenhypfs_handle xenhypfs_handle;

typedef struct
{
  int a;
} dirent;

void *foo(dirent **);

dirent *xenhypfs_readdir(xenhypfs_handle *fshdl,
                                         const char *path,
                                         unsigned int *num_entries)
{
    unsigned int n = 0, name_sz = 0;
    void *buf;
    dirent *ret_buf = 0; 
    dirent *dirent;

    buf = foo(&dirent);
    if (!buf)
        goto out;

    ret_buf = malloc(n * sizeof(*ret_buf) + name_sz);
    if (!ret_buf)
        goto out;

 out:
    free(buf);
    free(dirent);

    return ret_buf;
}

$ gcc core.c -c -O2 -Wall -Werror=use-after-free
core.c: In function ‘xenhypfs_readdir’:
core.c:33:12: error: pointer ‘ret_buf’ used after ‘free’
[-Werror=use-after-free]
   33 |     return ret_buf;
      |            ^~~~~~~
core.c:30:5: note: call to ‘free’ here
   30 |     free(buf);
      |     ^~~~~~~~~
cc1: some warnings being treated as errors

I believe the code is fine.

Reply via email to