From da392d27f2d8938bf002093bb94dc60beba6afd8 Mon Sep 17 00:00:00 2001 From: Comtea04 Date: Mon, 5 Oct 2026 11:44:56 +0900 Subject: utils: Handle realloc() failure in fdlist_add() fdlist_add() assigned the results of realloc() directly to list->owners and list->fds and doubled the capacity unconditionally, so on out-of-memory the arrays were leaked and the following stores wrote through a NULL pointer, crashing the daemon. Only update the pointers and the capacity once the reallocation succeeded. If it fails, log an error and leave the fd out of this poll() round; the main loop rebuilds the list on every iteration. A capacity of 0 (after fdlist_free()) now grows to 4 instead of staying 0. Co-Authored-By: Claude Opus 5.5 --- src/utils.c | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) (limited to 'src/utils.c') diff --git a/src/utils.c b/src/utils.c index 2cc5675..ec77234 100644 --- a/src/utils.c +++ b/src/utils.c @@ -50,9 +50,21 @@ void fdlist_create(struct fdlist *list) void fdlist_add(struct fdlist *list, enum fdowner owner, int fd, short events) { if(list->count == list->capacity) { - list->capacity *= 2; - list->owners = realloc(list->owners, sizeof(*list->owners) * list->capacity); - list->fds = realloc(list->fds, sizeof(*list->fds) * list->capacity); + int new_capacity = list->capacity ? list->capacity * 2 : 4; + enum fdowner *new_owners = realloc(list->owners, sizeof(*list->owners) * new_capacity); + if (!new_owners) { + util_error("%s: out of memory, not adding fd %d", __func__, fd); + return; + } + list->owners = new_owners; + struct pollfd *new_fds = realloc(list->fds, sizeof(*list->fds) * new_capacity); + if (!new_fds) { + /* owners is already larger, which is harmless; capacity stays unchanged */ + util_error("%s: out of memory, not adding fd %d", __func__, fd); + return; + } + list->fds = new_fds; + list->capacity = new_capacity; } list->owners[list->count] = owner; list->fds[list->count].fd = fd; -- cgit v1.1-32-gdbae