tests/memcheck.c: Avoid false positive -Wuse-after-free

Symptom was this compile warning from MinGW GCC 12:
> [..]/expat/tests/memcheck.c: In function ‘tracking_realloc’:
> [..]/expat/tests/memcheck.c:169:25: error: pointer ‘ptr’ may be used after ‘realloc’ [-Werror=use-after-free]
>   169 |       entry->allocation = ptr;
>       |       ~~~~~~~~~~~~~~~~~~^~~~~
> [..]/expat/tests/memcheck.c:166:25: note: call to ‘realloc’ here
>   166 |     entry->allocation = realloc(ptr, size);
>       |                         ^~~~~~~~~~~~~~~~~~

The warning is a false positive since the code was only using ptr
when realloc failed where it is documented that the original pointer is
not freed.

The workaround is to no longer override-and-restore entry->allocation
but to only write to it when realloc was successful.  The original
value was equal to ptr so the result is the same.
This commit is contained in:
Sebastian Pipping 2023-10-20 19:04:51 +02:00
parent a68399a05b
commit eeab6366b0

View file

@ -163,12 +163,11 @@ tracking_realloc(void *ptr, size_t size) {
alloc_tail = entry;
}
} else {
entry->allocation = realloc(ptr, size);
if (entry->allocation == NULL) {
/* Realloc semantics say the original is still allocated */
entry->allocation = ptr;
void *const reallocated = realloc(ptr, size);
if (reallocated == NULL) {
return NULL;
}
entry->allocation = reallocated;
}
entry->num_bytes = size;