4 ms·
snprintf. If you want to stick to the (safest) pattern of only passing the buffer size for the second parameter, you'd do this: snprintf(buf, sizeof buf,
by foxfluff 5y ago
snprintf. If you want to stick to the (safest) pattern of only passing the buffer size for the second parameter, you'd do this:
snprintf(buf, sizeof buf, "%.*s", prefix_length, source_str);
Example:
$ cat x.c
#include <stdio.h>
int main(void) {
char buf[128], tinybuf[5];
const char *copythis = "hello there\n";
snprintf(buf, sizeof buf, "%.*s", 5, copythis);
snprintf(tinybuf, sizeof tinybuf, "%.*s", 5, copythis);
printf("buf: %s\n", buf);
printf("tinybuf: %s\n", tinybuf);
}
$ cc -W -Wall -O3 x.c
x.c: In function ‘main’:
x.c:6:41: warning: ‘snprintf’ output truncated before the last format character [-Wformat-truncation=]
6 | snprintf(tinybuf, sizeof tinybuf, "%.*s", 5, copythis);
| ^
x.c:6:2: note: ‘snprintf’ output 6 bytes into a destination of size 5
6 | snprintf(tinybuf, sizeof tinybuf, "%.*s", 5, copythis);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$ ./a.out
buf: hello
tinybuf: hell
- LegionMammal978 5y agoThanks! I've never considered using snprintf in that way before; the default warnings are annoying, even though their intent is understandable.
- kazinator 5y agoThe warning isn't a false positive here; truncation is going on in that line: the chosen prefix doesn't fit into tinybuf.