diff --git a/Src/Modules/watch.c b/Src/Modules/watch.c index acc499518..d5053822b 100644 --- a/Src/Modules/watch.c +++ b/Src/Modules/watch.c @@ -560,21 +560,25 @@ readwtab(WATCH_STRUCT_UTMP **head, int initial_sz) # else /* !USER_PROCESS */ if (uptr->ut_name[0]) # endif /* !USER_PROCESS */ - { - uptr++; - if (++sz == wtabmax) { - uptr = (WATCH_STRUCT_UTMP *) - realloc(*head, (wtabmax *= 2) * sizeof(WATCH_STRUCT_UTMP)); - if (uptr == NULL) { - /* memory pressure - so stop consuming and use, what we have - * Other option is to exit() here, as zmalloc does on error */ - sz--; - break; - } - *head = uptr; - uptr += sz; - } - } +{ + uptr++; + if (++sz == wtabmax) { + // Use a temporary pointer to store the result of realloc + WATCH_STRUCT_UTMP *temp = realloc(*head, (wtabmax *= 2) * sizeof(WATCH_STRUCT_UTMP)); + + if (temp == NULL) { + // Memory allocation failed, decrement sz and break out of the loop + sz--; + break; + } + + // Successfully reallocated, update *head to the new memory block + *head = temp; + + // Recalculate the uptr after reallocating + uptr = *head + sz; + } +} } # ifdef HAVE_GETUTENT endutent();