diff options
author | John Ankarström <john@ankarstrom.se> | 2021-07-20 02:38:51 +0200 |
---|---|---|
committer | John Ankarström <john@ankarstrom.se> | 2021-07-21 11:19:55 +0200 |
commit | 8fc6be0a9b2dc6987f315a710b01531d99f68105 (patch) | |
tree | cb1559aa74df736ec22e36f4bf98d95471de852b | |
parent | 2d87adafb158932f8da44ef1864b8f8bacb859b1 (diff) | |
download | fref-8fc6be0a9b2dc6987f315a710b01531d99f68105.tar.gz |
Make pf more memory-safe
-rw-r--r-- | fref.lex | 14 |
1 files changed, 8 insertions, 6 deletions
@@ -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); |