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

From: David Laight

Date: Fri Nov 07 2025 - 04:12:52 EST


On Thu, 6 Nov 2025 21:38:33 -0800
Andrew Morton <akpm@xxxxxxxxxxxxxxxxxxxx> wrote:

> 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.

That is true for all the snprintf() functions.

> 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.

That adds the cost of a malloc, and I, like kasprintf() probably ends up
doing all the work of snprintf twice.

I'd be tempted to avoid the strlen() by passing in the offset.
So (say):
#define scnprintf_at(buf, len, off, ...) \
scnprintf((buf) + off, (len) - off, __VA_ARGS__)

Then you can chain calls, eg:
off = scnprintf(buf, sizeof buf, ....);
off += scnprintf_at(buf, sizeof buf, off, ....);

David