[PATCH stalld 37/52] stalld: fix buffer underflow in read_proc_stat

Wander Lairson Costa <[email protected]> Mon, 8 Jun 2026 15:31:47 -0300
Newsgroups org.kernel.vger.linux-rt-users
Message-ID <[email protected]>
The null termination of the buffer after the read loop writes to
buffer[position-1] without checking that position is non-zero. If
read() returns zero on the first call, position remains at its
initial value of zero and the write goes to buffer[-1], corrupting
the byte immediately before the buffer on the stack.

Add a guard to only null-terminate when at least one byte was read.

Signed-off-by: Wander Lairson Costa <[email protected]>
---
 src/utils.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/src/utils.c b/src/utils.c
index 90a0024..5d54ae9 100644
--- a/src/utils.c
+++ b/src/utils.c
@@ -1376,7 +1376,8 @@ int read_proc_stat(char *buffer, int size)
 
 	} while (retval > 0 && position < size);
 
-	buffer[position-1] = '\0';
+	if (position > 0)
+		buffer[position-1] = '\0';
 
 	close(fd);
 
-- 
2.54.0