From 0a1cfca0f41ca4ee5d981253b8f151c67aacf4f6 Mon Sep 17 00:00:00 2001 From: Michael Forney Date: Wed, 9 Jun 2021 14:34:57 -0700 Subject: [PATCH] Avoid creating out-of-bounds pointer when checking for seprintf truncation It is technically undefined behavior (see C11 6.5.6p8) to construct a pointer more than one past the end of an array. To prevent this, compare n with the remaining space in the array before adding to ptr. --- chat.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chat.h b/chat.h index e75112a..327262b 100644 --- a/chat.h +++ b/chat.h @@ -52,8 +52,8 @@ static inline char *seprintf(char *ptr, char *end, const char *fmt, ...) { int n = vsnprintf(ptr, end - ptr, fmt, ap); va_end(ap); if (n < 0) return NULL; - ptr += n; - return (ptr > end ? end : ptr); + if (n > end - ptr) return end; + return ptr + n; } enum Attr {