Home

snprintf

snprintf is a function in the C standard library that formats a sequence of characters and stores them in the character array pointed to by str. It is designed to prevent buffer overflows by enforcing a maximum number of characters to write, as specified by the size parameter. The function follows the printf formatting rules and formats the provided arguments according to the format string.

It writes at most size-1 characters from the formatted output and always terminates the destination with a

Special case: if size is 0, nothing is written, but snprintf still returns the length of the

snprintf is defined in the C99 standard and is widely implemented across platforms, including GNU C Library,

null
character,
provided
size
is
nonzero.
The
return
value
is
the
number
of
characters
that
would
have
been
written
if
enough
space
had
been
available,
not
counting
the
terminating
null
terminator.
If
the
returned
value
is
greater
than
or
equal
to
size,
the
output
was
truncated.
would-be
output.
The
function
is
part
of
the
printf
family
and
has
a
related
variant,
vsnprintf,
which
accepts
a
va_list
instead
of
variadic
arguments.
musl,
BSD
libc,
and
MSVC.
It
is
commonly
used
as
a
safer
alternative
to
functions
like
sprintf
when
the
destination
buffer
size
is
known,
enabling
formatted
output
without
risking
buffer
overflow.