I'm trying to learn about the snprintf
and found this answer with the example:
char buf[20] = "";
char *cur = buf, * const end = buf + sizeof buf;
cur += snprintf(cur, end-cur, "%s", "foo");
printf("%s\n", buf);
if (cur < end) {
cur += snprintf(cur, end-cur, "%s", " bar");
}
printf("%s\n", buf);
free(str);
The thing that is not clear to me is that we allocate a fixed hardcoded buffer size which seems suffer from buffer overflow. In the N1570 I found that (7.21.6.5)
1
#include <stdio.h> int snprintf(char * restrict s, size_t n, const char * restrict format, ...);
2 The snprintf function is equivalent to fprintf, except that the output is written into an array (specified by argument s) rather than to a stream. If n is zero, nothing is written, and s may be a null pointer.
So to me it appears as the idiomatic usage would be as follows:
int need_space = snprintf(NULL, 0, "abs %s", "fgh") + 1; //How much to allocate?
char *const str = malloc(need_space * sizeof(char)); //allocate
int written = snprintf(str, need_space, "abs %s", "fgh"); //do format
printf("Need space = %d, written = %d\n", need_space, written);
printf("%s\n", str);
Or this is not common and has another problem?
"RETURN"
portion. You validate the return against the buffer size. – David C. Rankinsizeof(char)
is 1 – brunoasprintf()
andvasprintf()
; using these can be a good idea. – Jonathan Leffler