obmc-console: Address more instances of realloc() with size 0
There are some portability concerns around the behavior of passing
a zero size to realloc*() APIs. One instance caught by valgrind was
fixed in 2f1abc37384d ("Fix realloc() with size 0"). All invocations of
realloc*() APIs were evaluated, and those fixed here are the ones that
were at risk.
There's a broader problem of the code-base assuming realloc*() calls
don't return NULL (and malloc() also). The returned pointer is usually
written into the pointer object passed as the first argument, which
means the existing object would be leaked. Fixing that is a bigger
endeavor as the callers of the functions invoking realloc*() are often
written with the assumption that the result is not NULL. However, with
this change, at least one of the realloc*() concerns is put to rest.
Change-Id: I5dd6f4f8cc3164e400c87ea37afc350840a1865d
Signed-off-by: Andrew Jeffery <andrew@codeconstruct.com.au>
diff --git a/console-server.c b/console-server.c
index ef52e57..aec7a35 100644
--- a/console-server.c
+++ b/console-server.c
@@ -689,8 +689,14 @@
memmove(&console->pollers[i], &console->pollers[i + 1],
sizeof(*console->pollers) * (console->n_pollers - i));
- console->pollers = reallocarray(console->pollers, console->n_pollers,
- sizeof(*console->pollers));
+ if (console->n_pollers == 0) {
+ free(console->pollers);
+ console->pollers = NULL;
+ } else {
+ console->pollers = reallocarray(console->pollers,
+ console->n_pollers,
+ sizeof(*console->pollers));
+ }
/* NOLINTEND(bugprone-sizeof-expression) */
/* ... and the pollfds array */
diff --git a/socket-handler.c b/socket-handler.c
index 3abdc97..6268fca 100644
--- a/socket-handler.c
+++ b/socket-handler.c
@@ -97,8 +97,13 @@
/* NOLINTBEGIN(bugprone-sizeof-expression) */
memmove(&sh->clients[idx], &sh->clients[idx + 1],
sizeof(*sh->clients) * (sh->n_clients - idx));
- sh->clients =
- reallocarray(sh->clients, sh->n_clients, sizeof(*sh->clients));
+ if (sh->n_clients == 0) {
+ free(sh->clients);
+ sh->clients = NULL;
+ } else {
+ sh->clients = reallocarray(sh->clients, sh->n_clients,
+ sizeof(*sh->clients));
+ }
/* NOLINTEND(bugprone-sizeof-expression) */
}