From 8fc6be0a9b2dc6987f315a710b01531d99f68105 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?John=20Ankarstr=C3=B6m?= <john@ankarstrom.se>
Date: Tue, 20 Jul 2021 02:38:51 +0200
Subject: Make pf more memory-safe

---
 fref.lex | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)

diff --git a/fref.lex b/fref.lex
index d3b3661..8d640ae 100644
--- a/fref.lex
+++ b/fref.lex
@@ -157,20 +157,22 @@ harvard()
 	CL(e.xx);
 }
 
-/* Print formatted text if given strings are non-empty. */
+/* Print formatted text if given fields are non-empty. */
 int
 pf(char *fmt, ...)
 {
 	char *buf, *p;
-	int n;
+	int n, sz;
 	va_list ap;
 
-	n = 0;
-	for(p = fmt; *p; p++)
+	/* Count given fields. */
+	for(n = 0, p = fmt; *p; p++)
 		if(*p == '%')
 			n++;
 
-	if(!(buf = malloc(strlen(fmt)+n*MAX+1)))
+	/* Allocate enough memory to fit the given fields. */
+	sz = strlen(fmt)+n*MAX+1;
+	if(!(buf = malloc(sz)))
 		err(1, "malloc");
 
 	va_start(ap, fmt);
@@ -180,7 +182,7 @@ pf(char *fmt, ...)
 			p = va_arg(ap, char *);
 			if(!p || !*p)
 				return 0;
-			strcat(buf, p);
+			strncat(buf, p, sz-1);
 			break;
 		default:
 			strncat(buf, fmt, 1);
-- 
cgit v1.2.3