diff options
author | Kaz Kylheku <kaz@kylheku.com> | 2024-01-16 17:17:13 -0800 |
---|---|---|
committer | Kaz Kylheku <kaz@kylheku.com> | 2024-01-16 17:17:13 -0800 |
commit | 475867a8b6744b76fbf7c6ace582fa6503c077f1 (patch) | |
tree | d67084bd250bd7cf8d8c0602ff4ab8d25d8bf38c /lib.c | |
parent | bf1e14cf2c4cae4300936cad995d41e498a54701 (diff) | |
download | txr-475867a8b6744b76fbf7c6ace582fa6503c077f1.tar.gz txr-475867a8b6744b76fbf7c6ace582fa6503c077f1.tar.bz2 txr-475867a8b6744b76fbf7c6ace582fa6503c077f1.zip |
lib: avoid realloc with zero size.
I spotted in the N3096 draft of ISO C (April 2023) that
a zero size in realloc is no longer defined behavior,
like it used to be. I don't know exactly when it changed;
in C99 it is not mentioned. We call realloc only in
one place, so we can defend agains this.
* lib.c (chk_realloc): If the new size is zero, we
implement the C99 and older semantics: deallocate the
object, and then behave like malloc(0). In other
cases, we use realloc.
Diffstat (limited to 'lib.c')
-rw-r--r-- | lib.c | 16 |
1 files changed, 13 insertions, 3 deletions
@@ -4509,12 +4509,22 @@ mem_t *chk_calloc(size_t n, size_t size) mem_t *chk_realloc(mem_t *old, size_t size) { - mem_t *newptr = convert(mem_t *, realloc(old, size)); + mem_t *newptr = 0; assert (!async_sig_enabled); - if (size != 0 && newptr == 0) - oom(); + /* We avoid calling realloc with size == 0. + * It was okay in C99; 2023 draft of ISO C says this is undefined. + */ + if (size == 0) { + free(old); + newptr = convert(mem_t *, malloc(0)); + } else { + newptr = convert(mem_t *, realloc(old, size)); + if (newptr == 0) + oom(); + } + malloc_bytes += size; return newptr; } |