From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: by sourceware.org (Postfix, from userid 48) id 82C0E385840B; Wed, 10 Aug 2022 14:16:45 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org 82C0E385840B From: "gcc.gnu.org at aydos dot de" To: gcc-bugs@gcc.gnu.org Subject: [Bug middle-end/106578] New: spurious -Wuse-after-free=2 after conditional free() Date: Wed, 10 Aug 2022 14:16:45 +0000 X-Bugzilla-Reason: CC X-Bugzilla-Type: new X-Bugzilla-Watch-Reason: None X-Bugzilla-Product: gcc X-Bugzilla-Component: middle-end X-Bugzilla-Version: 12.1.1 X-Bugzilla-Keywords: X-Bugzilla-Severity: normal X-Bugzilla-Who: gcc.gnu.org at aydos dot de X-Bugzilla-Status: UNCONFIRMED X-Bugzilla-Resolution: X-Bugzilla-Priority: P3 X-Bugzilla-Assigned-To: unassigned at gcc dot gnu.org X-Bugzilla-Target-Milestone: --- X-Bugzilla-Flags: X-Bugzilla-Changed-Fields: bug_id short_desc product version bug_status bug_severity priority component assigned_to reporter target_milestone Message-ID: Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: quoted-printable X-Bugzilla-URL: http://gcc.gnu.org/bugzilla/ Auto-Submitted: auto-generated MIME-Version: 1.0 X-BeenThere: gcc-bugs@gcc.gnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: Gcc-bugs mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Wed, 10 Aug 2022 14:16:45 -0000 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=3D106578 Bug ID: 106578 Summary: spurious -Wuse-after-free=3D2 after conditional free() Product: gcc Version: 12.1.1 Status: UNCONFIRMED Severity: normal Priority: P3 Component: middle-end Assignee: unassigned at gcc dot gnu.org Reporter: gcc.gnu.org at aydos dot de Target Milestone: --- I am new to GCC's components, so feel free to rename the headers if I classified the bug wrong. The following code throws the `use-after-free` error: ``` #include void *buf =3D NULL; size_t buf_size =3D 0; int main() { void *tmp =3D buf; buf =3D realloc(tmp, 10); // Realloc returns a pointer to the new object, or a null pointer if the // new object could not be allocated. Free the original pointer // to avoid memory leak in latter case. if (!buf) free(tmp); } ``` ``` $ gcc -Wall -Wuse-after-free=3D2 main.c main.c: In function =E2=80=98main=E2=80=99: main.c:15:17: warning: pointer =E2=80=98tmp=E2=80=99 may be used after =E2= =80=98realloc=E2=80=99 [-Wuse-after-free] 15 | free(tmp); | ^~~~~~~~~ main.c:9:15: note: call to =E2=80=98realloc=E2=80=99 here 9 | buf =3D realloc(tmp, 10); | ^~~~~~~~~~~~~~~~ ``` A workaround is to `realloc` directly `buf` and use `tmp` for the return va= lue of `realloc`: ``` #include void *buf =3D NULL; size_t buf_size =3D 0; int main() { void *tmp =3D buf; tmp =3D realloc(buf, 10); if (!tmp) free(buf); } ``` >>From what I saw in other bugs this one may also be related to the meta-bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=3D104075. Can someone confirm this case?=