https://gcc.gnu.org/bugzilla/show_bug.cgi?id=110501
Bug ID: 110501 Summary: Invalid use-after-free / realloc Product: gcc Version: 12.3.1 Status: UNCONFIRMED Severity: normal Priority: P3 Component: analyzer Assignee: dmalcolm at gcc dot gnu.org Reporter: cheyenne.wills at gmail dot com Target Milestone: --- Created attachment 55433 --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=55433&action=edit testcase.i I've ran into a problem where gcc-12 (and later versions) is producing a false positive on a use-after-free following a realloc. The attached information obtained from a current gentoo system using gcc (Gentoo 12.3.1_p20230526 p2) 12.3.1 20230526) gcc -v -save-temps -Wall -c testcase.c &> testcase.log I've been able to duplicate the problem on godbolt.org using different versions of gcc from gcc 12.1 through gcc master (I also tried various architectures, x86_64, arm, etc.). godbolt's gcc 11 does work as expected. The gist of the problem is: --- S->sp = realloc(p, size * 2); if (S->sp == NULL && size != 0) { free(p); /* << is flagged as a use after free */ return 0; } --- However the following works: --- char *t; t = realloc(p, size * 2); if (t == NULL && size != 0) { free(p); /* << is not flagged as a use after free */ return 0; } S->sp = t; --- The provided testcase contains 3 simple functions. The function fail1 and fail2 has code that shows the invalid use-after-free, while the function succeeds has code that does not produce the use-after-free message. The only difference between the failed functions and the success that the success function uses a stack based temporary variable to hold the result of the realloc. == $ $ gcc -Wall -Wextra -c testcase.c testcase.c: In function ‘fail1’: testcase.c:10:9: warning: pointer ‘p’ may be used after ‘realloc’ [-Wuse-after-free] 10 | free(p); /* Is flagged as a use after free */ | ^~~~~~~ testcase.c:8:13: note: call to ‘realloc’ here 8 | S->sp = realloc(p, size*2); | ^~~~~~~~~~~~~~~~~~ testcase.c: In function ‘fail2’: testcase.c:20:9: warning: pointer ‘p’ may be used after ‘realloc’ [-Wuse-after-free] 20 | free(p); /* Is flagged as a use after free */ | ^~~~~~~ testcase.c:18:9: note: call to ‘realloc’ here 18 | t = realloc(p, size*2); | ^~~~~~~~~~~~~~~~~~ $ == The problem was originally discovered while building from openafs's master branch (www.openafs.org) with a gcc-13 compiler. src/external/heimdal/krb5/crypto.c:1157:9: error: pointer ‘p’ may be used after ‘realloc’ [-Werror=use-after-free] 1157 | free(p); | ^~~~~~~ src/external/heimdal/krb5/crypto.c:1155:20: note: call to ‘realloc’ here 1155 | result->data = realloc(p, sz); | ^~~~~~~~~~~~~~ The failing code is part of an "external library" from the heimdal project.