Re: [PATCH 1/4] lib/sprintf: add scnprintf_append() helper function

From: Andrew Morton

Date: Fri Nov 07 2025 - 00:38:34 EST


On Fri, 7 Nov 2025 13:16:13 +0800 Junrui Luo <moonafterrain@xxxxxxxxxxx> wrote:

> +/**
> + * scnprintf_append - Append a formatted string to a buffer
> + * @buf: The buffer to append to (must be null-terminated)
> + * @size: The size of the buffer
> + * @fmt: Format string
> + * @...: Arguments for the format string
> + *
> + * This function appends a formatted string to an existing null-terminated
> + * buffer. It is safe to use in a chain of calls, as it returns the total
> + * length of the string.
> + *
> + * Returns: The total length of the string in @buf

It wouldn't hurt to describe the behavior when this runs out of space
in *buf.



The whole thing is a bit unweildy - how much space must the caller
allocate for `buf'? I bet that's a wild old guess.


I wonder if we should instead implement a kasprintf() version of this
which reallocs each time and then switch all the callers over to that.


um,

int kasprintf_append(char **pbuf, gfp_t gfp_flags, const char *fmt, ...);


int caller()
{
char *buf = NULL;
while (...) {
x = kasprintf_append(&buf, GFP_KERNEL, "%whatever", stuff...);
if (x == -ENOMEM)
return x;
}
...
kfree(buf);
}

So much nicer!