aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJohn Ankarström <john@ankarstrom.se>2021-07-20 02:38:51 +0200
committerJohn Ankarström <john@ankarstrom.se>2021-07-21 11:19:55 +0200
commit8fc6be0a9b2dc6987f315a710b01531d99f68105 (patch)
treecb1559aa74df736ec22e36f4bf98d95471de852b
parent2d87adafb158932f8da44ef1864b8f8bacb859b1 (diff)
downloadfref-8fc6be0a9b2dc6987f315a710b01531d99f68105.tar.gz
Make pf more memory-safe
-rw-r--r--fref.lex14
1 files 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);