Repace malloc(X * Y) with reallocarray which checks for potential overflows.