[Bug middle-end/106578] New: spurious -Wuse-after-free=2 after conditional free()
gcc.gnu.org at aydos dot de
gcc-bugzilla@gcc.gnu.org
Wed Aug 10 14:16:45 GMT 2022
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=106578
Bug ID: 106578
Summary: spurious -Wuse-after-free=2 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 <stdlib.h>
void *buf = NULL;
size_t buf_size = 0;
int main() {
void *tmp = buf;
buf = 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=2 main.c
main.c: In function ‘main’:
main.c:15:17: warning: pointer ‘tmp’ may be used after ‘realloc’
[-Wuse-after-free]
15 | free(tmp);
| ^~~~~~~~~
main.c:9:15: note: call to ‘realloc’ here
9 | buf = realloc(tmp, 10);
| ^~~~~~~~~~~~~~~~
```
A workaround is to `realloc` directly `buf` and use `tmp` for the return value
of `realloc`:
```
#include <stdlib.h>
void *buf = NULL;
size_t buf_size = 0;
int main() {
void *tmp = buf;
tmp = 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=104075.
Can someone confirm this case?
More information about the Gcc-bugs
mailing list