🌐
GeeksforGeeks
geeksforgeeks.org › c language › snprintf-c-library
snprintf() in C - GeeksforGeeks
March 7, 2025 - In C, snprintf() function is a standard library function that is used to print the specified string till a specified length in the specified format.
🌐
Cplusplus
cplusplus.com › reference › cstdio › snprintf
snprintf
<cstdio> snprintf · function · <cstdio> int snprintf ( char * s, size_t n, const char * format, ... ); Write formatted output to sized buffer ·
Discussions

c - snprintf usage for making up formatted strings - Stack Overflow
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"); print... More on stackoverflow.com
🌐 stackoverflow.com
c - snprintf() without format specifier? - Stack Overflow
No you dont, but it's generally considered a good idea especially if there's any chance of passing user-input text to snprintf(). More on stackoverflow.com
🌐 stackoverflow.com
c - Using snprintf to print an array? Alternatives? - Stack Overflow
Is it at all possible to use snprintf to print an array? I know that it can take multiple arguments, and it expects at least as many as your formatting string suggests, but if I just give it 1 More on stackoverflow.com
🌐 stackoverflow.com
examples of snprintf advantages over printf?
They don't serve the same purpose, printf() writes to stdout and snprintf() writes to a buffer. It doesn't have to do with efficiency. char url[256]; const char ip_addr[] = "11.12.13.14"; snprintf(url, 256, "http://%s/index.html", ip_addr); printf("Getting url <%s>\n", url); http_get(url); In this example, snprintf() is used to build a url, and printf() is used to print the url to stdout. More on reddit.com
🌐 r/C_Programming
18
1
March 7, 2014
🌐
Samba
samba.org › rsync › doxygen › head › snprintf_8c-source.html
snprintf.c Source File
"snprintf l1 != l2 (%d %d) %s\n", l1, l2, fp_fmt[x]); 00878 fail++; 00879 } 00880 num++; 00881 } 00882 } 00883 00884
🌐
Microsoft Learn
learn.microsoft.com › en-us › cpp › c-runtime-library › reference › snprintf-snprintf-snprintf-l-snwprintf-snwprintf-l
snprintf, _snprintf, _snprintf_l, _snwprintf, _snwprintf_l | Microsoft Learn
October 3, 2025 - Access to this page requires authorization. You can try changing directories. ... Writes formatted data to a string. More secure versions of these functions are available; see _snprintf_s, _snprintf_s_l, _snwprintf_s, _snwprintf_s_l.
🌐
cppreference.com
en.cppreference.com › c › io › fprintf
printf, fprintf, sprintf, snprintf, printf_s, fprintf_s, sprintf_s, snprintf_s - cppreference.com
const char fmt[] = "sqrt(2) = %f"; int sz = snprintf(NULL, 0, fmt, sqrt(2)); char buf[sz + 1]; // note +1 for terminating null byte snprintf(buf, sizeof buf, fmt, sqrt(2));
🌐
IBM
ibm.com › docs › en › i › 7.5.0
snprintf() — Print Formatted Data to Buffer - IBM Documentation
September 29, 2025 - This example uses snprintf() to format and print various data. #include <stdio.h> char buffer[200]; int i, j; double fp; char *s = "baltimore"; char c; int main(void) { c = 'l'; i = 35; fp = 1.7320508; /* Format and print various data */ j = snprintf(buffer, 6, "%s\n", s); j += snprintf(buffer+j, 6, "%c\n", c); j += snprintf(buffer+j, 6, "%d\n", i); j += snprintf(buffer+j, 6, "%f\n", fp); printf("string:\n%s\ncharacter count = %d\n", buffer, j); } /********************* Output should be similar to: ************* string: baltil 35 1.732 character count = 15 */
Find elsewhere
🌐
W3Schools
w3schools.com › c › ref_stdio_snprintf.php
C stdio snprintf() Function
The snprintf() function writes a formatted string followed by a \0 null terminating character into a char array.
🌐
O'Reilly
oreilly.com › library › view › c-in-a › 0596006977 › re210.html
snprintf - C in a Nutshell [Book]
December 16, 2005 - #include <stdio.h> intsnprintf( ... function is similar to printf(), but writes its output as a string in the buffer referenced by the first pointer argument, dest, rather than to stdout....
Authors   Peter PrinzTony Crawford
Published   2005
Pages   618
🌐
Linux Man Pages
linux.die.net › man › 3 › snprintf
snprintf(3): formatted output conversion - Linux man page
Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings). The functions snprintf() and vsnprintf() do not write more than size bytes (including the terminating null byte ('\0')).
Top answer
1 of 2
4

The 2x call to snprintf() is a common idiom.

... has another problem?

Problems lie in the corners

Format maintenance

The below suffers from a repeated format - prone to breaking as code ages and and only one line is changed.

// Oops!
int need_space = snprintf(NULL, 0, "abs %s", "fgh") + 1;
char *const str = malloc(need_space * sizeof(char));
int written = snprintf(str, need_space, "abs %s ", "fgh");

Did you notice the difference?

Better to state the format once.

#define FMT_ABS_S "abs %s"
int need_space = snprintf(NULL, 0, FMT_ABS_S, "fgh");
char *const str = malloc(sizeof *str * (need_space + 1u));
int written = snprintf(str, need_space + 1, FMT_ABS_S, "fgh");

Volatility

Code needs to insure the values do not change (non-volatile) between the 2 calls and special concern arise in multi-threaded applications.

Error checking

Code lacked checks. Yet even with checks, how to even handle unexpected results - perhaps just bail?

static const char *fmt_s = "abs %s";
int length = snprintf(NULL, 0, fmt_s, "fgh");
if (length < 0) {
  Handle_EncodingError();
}
char *str = malloc(sizeof *str * (length + 1u));
if (str == NULL) {
  Handle_OutOfMemory();
}
int written = snprintf(str, length + 1, fmt_s, "fgh");
if (written < 0 || written > length) {
  Handle_Error();
}
...
free(str);

Going twice though

2 calls can be wasteful in select situations, yet commonly the impact is less than thought. @Jonathan Leffler

Yet for me, the "what to do if allocation fails" is a show stopper anyways and code reports the error and maybe exit.

Selectively, once is enough

When the s*printf() format is tightly controlled, I see 1 call as sufficient.

// int to string

#define LOG2_N 28
#define LOG2_D 93
// Number of char needed for a string of INT_MIN is log10(bit width) + 3
#define INT_SIZE ((sizeof(int)*CHAR_BIT-1)*LOG2_N/LOG2_D + 3)

char s[INT_SIZE * 2];  // I like to use 2x to handle locale issues, no need to be stingy here.

int len = snprintf(s, sizeof s, "%d", i);

if (len < 0 || (unsigned) len >= sizeof s) {
  Handle_VeryUnusualFailure();
}
2 of 2
0

In addition to @chux precise answer, it should be noted that the posted code has potential undefined behavior:

char buf[20] = "";                                // initialization is optional
char *cur = buf, * const end = buf + sizeof buf;  // cumbersome combined definitions
cur += snprintf(cur, end-cur, "%s", "foo");       // cur may be increased beyond the end of the array
printf("%s\n", buf);                              // no problem here
if (cur < end) {                                  // undefined behavior if cur points beyond the end of the array
    cur += snprintf(cur, end-cur, "%s", " bar");  // again cur may be increased too far.
}
printf("%s\n", buf);                              // OK
free(str);                                        // definition for str is not posted

If snprintf truncates the output, cur will be increased to point beyond the end of the array buf, which has undefined behavior. Comparing cur and end is meaningless if they do not point the same array or to the element just after the array.

It is easy to fix these problems:

char buf[20];
size_t size = sizeof buf;
size_t pos = 0;
int n = snprintf(buf + pos, size - pos, "%s", "foo");
if (n < 0) {
    // handle this unlikely error
    *buf = '\0';
} else {
    pos += n;
}
printf("%s\n", buf);
if (pos < size) {
    n = snprintf(buf + pos, size - pos, "%s", " bar");
}
printf("%s\n", buf);
🌐
GitHub
github.com › taviso › lotusdrv › blob › master › snprintf.c
lotusdrv/snprintf.c at master · taviso/lotusdrv
* snprintf.c - a portable implementation of snprintf · * * AUTHOR · * Mark Martinec <mark.martinec@ijs.si>, April 1999. * * Copyright 1999, Mark Martinec. All rights reserved.
Author   taviso
🌐
Sternum IoT
sternumiot.com › home › sprintf and snprintf c functions – syntax, examples, and security best practices
sprintf and snprintf C Functions | Syntax, Examples & Security Best Practices| Sternum IoT
June 4, 2023 - What ןs the sprintf() Function In C programming language the sprintf() function is used for formatting strings through the merger of text with variables, numbers, etc. The sprintf() function accepts a format string as its initial argument, ...
🌐
University of Washington
ctan.math.washington.edu › tex-archive › graphics › sam2p › snprintf.c
snprintf.c
is included * -- minimal dependencies: not even -lm is required * -- can print floating point numbers * -- can print `long long' and `long double' * -- C99 semantics (NULL arg for vsnprintf OK, always returns the length * that would have been printed) * -- provides all vsnprintf(), snprintf(), vasprintf(), asprintf() */ /**** pts: sam2p-specific defines ****/ #include "snprintf.h" /* #include
🌐
SAS
support.sas.com › documentation › onlinedoc › sasc › doc750 › html › lr1 › z2056522.htm
Function Descriptions : snprintf
The snprintf function returns an integer value that equals, in magnitude, the number of characters written to the area addressed by dest . If the value returned is negative, then either the maxlen character limit was reached or some other error, such as an invalid format specification, has occurred.
🌐
IBM
ibm.com › docs › en › zos › 2.5.0
snprintf() — Format and write data - IBM Documentation
April 28, 2023 - Your comment was saved locally, if not in an incognito browser, and will be available when attempting to submit feedback again. ... A newer version of this product documentation is available. You are viewing an older version. ... #include <stdio.h> int snprintf(char *__restrict__ s, size_t n, const char *__restrict__ format, ...);
🌐
Reddit
reddit.com › r/c_programming › examples of snprintf advantages over printf?
r/C_Programming on Reddit: examples of snprintf advantages over printf?
March 7, 2014 -

I know what snprintf does and how it works but I think I really need some examples of how it would be used in terms of efficiency in a program. Any help would be appreciated. :D

Edit: so printf and snprintf cannot be compared in terms of efficiency..oops. Still looking for examples for snprintf and maybe sprint f and why you would use it. Thank's guys!!

🌐
CS50
manual.cs50.io › 3 › snprintf
snprintf - CS50 Manual Pages
The complete conversion specification is '%%'. Upon successful return, these functions return the number of bytes printed (excluding the null byte used to end output to strings). The functions snprintf() and vsnprintf() do not write more than size bytes (including the terminating null byte ('\0')).