3 ms·
Regarding buf[len] = '\0', I've personally had to use it in many scenarios following strncpy, which doesn't add a null terminator if the maximum length is reach
by LegionMammal978 5y ago
Regarding buf[len] = '\0', I've personally had to use it in many scenarios following strncpy, which doesn't add a null terminator if the maximum length is reached. Do you know of any simpler way of getting a prefix up to a certain length?
- foxfluff 5y agosnprintf. 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.