From 668ecb8e943007767cdd528982183d0409e91312 Mon Sep 17 00:00:00 2001 From: "peng.li24" Date: Thu, 4 Jun 2026 08:49:24 +0000 Subject: [PATCH] fix: prevent unsigned integer underflow when usage exceeds memory limit When usage > limit, (limit - usage) wraps around to a massive unsigned value (~18 EB). Clamp both free and used so that free + used = total always holds, preventing corrupted values in monitoring tools. Fixes #200 Signed-off-by: peng.li24 Co-Authored-By: Claude Opus 4.7 --- src/nvml/hook.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/nvml/hook.c b/src/nvml/hook.c index 0bc16d31..a0511670 100644 --- a/src/nvml/hook.c +++ b/src/nvml/hook.c @@ -353,16 +353,17 @@ nvmlReturn_t _nvmlDeviceGetMemoryInfo(nvmlDevice_t device,void* memory,int versi return NVML_SUCCESS; } } else { + size_t clamped = (usage > limit) ? limit : usage; switch (version) { case 1: - ((nvmlMemory_t*)memory)->free = (limit-usage); + ((nvmlMemory_t*)memory)->free = limit - clamped; ((nvmlMemory_t*)memory)->total = limit; - ((nvmlMemory_t*)memory)->used = usage; + ((nvmlMemory_t*)memory)->used = clamped; return NVML_SUCCESS; case 2: - ((nvmlMemory_v2_t *)memory)->free = (limit-usage); + ((nvmlMemory_v2_t *)memory)->free = limit - clamped; ((nvmlMemory_v2_t *)memory)->total = limit; - ((nvmlMemory_v2_t *)memory)->used = usage; + ((nvmlMemory_v2_t *)memory)->used = clamped; return NVML_SUCCESS; } }