Use sprintf. (This is NOT safe, but OP asked for an ANSI C answer. See the comments for a safe version.)

int sprintf ( char * str, const char * format, ... );

Write formatted data to string Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by str.

The size of the buffer should be large enough to contain the entire resulting string (see snprintf for a safer version).

A terminating null character is automatically appended after the content.

After the format parameter, the function expects at least as many additional arguments as needed for format.

Parameters:

str

Pointer to a buffer where the resulting C-string is stored. The buffer should be large enough to contain the resulting string.

format

C string that contains a format string that follows the same specifications as format in printf (see printf for details).

... (additional arguments)

Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n). There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.

Example:

// Allocates storage
char *hello_world = (char*)malloc(13 * sizeof(char));
// Prints "Hello world!" on hello_world
sprintf(hello_world, "%s %s!", "Hello", "world");
Answer from akappa on Stack Overflow
Top answer
1 of 8
137

Use sprintf. (This is NOT safe, but OP asked for an ANSI C answer. See the comments for a safe version.)

int sprintf ( char * str, const char * format, ... );

Write formatted data to string Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by str.

The size of the buffer should be large enough to contain the entire resulting string (see snprintf for a safer version).

A terminating null character is automatically appended after the content.

After the format parameter, the function expects at least as many additional arguments as needed for format.

Parameters:

str

Pointer to a buffer where the resulting C-string is stored. The buffer should be large enough to contain the resulting string.

format

C string that contains a format string that follows the same specifications as format in printf (see printf for details).

... (additional arguments)

Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n). There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.

Example:

// Allocates storage
char *hello_world = (char*)malloc(13 * sizeof(char));
// Prints "Hello world!" on hello_world
sprintf(hello_world, "%s %s!", "Hello", "world");
2 of 8
36

If you have a POSIX-2008 compliant system (any modern Linux), you can use the safe and convenient asprintf() function: It will malloc() enough memory for you, you don't need to worry about the maximum string size. Use it like this:

char* string;
if(0 > asprintf(&string, "Formatting a number: %d\n", 42)) return error;
log_out(string);
free(string);

This is the minimum effort you can get to construct the string in a secure fashion. The sprintf() code you gave in the question is deeply flawed:

  • There is no allocated memory behind the pointer. You are writing the string to a random location in memory!

  • Even if you had written

    char s[42];
    

    you would be in deep trouble, because you can't know what number to put into the brackets.

  • Even if you had used the "safe" variant snprintf(), you would still run the danger that your strings gets truncated. When writing to a log file, that is a relatively minor concern, but it has the potential to cut off precisely the information that would have been useful. Also, it'll cut off the trailing endline character, gluing the next log line to the end of your unsuccessfully written line.

  • If you try to use a combination of malloc() and snprintf() to produce correct behavior in all cases, you end up with roughly twice as much code than I have given for asprintf(), and basically reprogram the functionality of asprintf().


If you are looking at providing a wrapper of log_out() that can take a printf() style parameter list itself, you can use the variant vasprintf() which takes a va_list as an argument. Here is a perfectly safe implementation of such a wrapper:

//Tell gcc that we are defining a printf-style function so that it can do type checking.
//Obviously, this should go into a header.
void log_out_wrapper(const char *format, ...) __attribute__ ((format (printf, 1, 2)));

void log_out_wrapper(const char *format, ...) {
    char* string;
    va_list args;

    va_start(args, format);
    if(0 > vasprintf(&string, format, args)) string = NULL;    //this is for logging, so failed allocation is not fatal
    va_end(args);

    if(string) {
        log_out(string);
        free(string);
    } else {
        log_out("Error while logging a message: Memory allocation failed.\n");
    }
}
🌐
GeeksforGeeks
geeksforgeeks.org › c language › format-specifiers-in-c
Format Specifiers in C - GeeksforGeeks
1 week ago - We can use the %o format specifier in the C program to print or take input for the unsigned octal integer number. ... The %x format specifier is used in the formatted string for hexadecimal integers.
🌐
Cprogramming
cprogramming.com › tutorial › printf-format-strings.html
Printf format strings - Cprogramming.com
How to begin Get the book · C tutorial C++ tutorial Game programming Graphics programming Algorithms More tutorials
🌐
Microsoft Learn
learn.microsoft.com › en-us › cpp › c-runtime-library › format-specification-syntax-printf-and-wprintf-functions
Format Specification Syntax: `printf` and `wprintf` Functions | Microsoft Learn
Access to this page requires authorization. You can try changing directories. ... The various printf and wprintf functions take a format string and optional arguments and produce a formatted sequence of characters for output. The format string contains zero or more directives, which are either literal characters for output or encoded conversion specifications that describe how to format an argument in the output.
🌐
Cplusplus
cplusplus.com › reference › cstdio › printf
Cplusplus
If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers. ... C string that contains the text to be written to stdout.
🌐
Vaia
vaia.com › string formatting c
String Formatting C: Techniques & Examples | Vaia
December 12, 2024 - String formatting in C is a crucial technique that allows programmers to display or store text with embedded variables and control over the output format, primarily using functions like `printf()` and `sprintf()`. These functions utilize format specifiers, such as `%d` for integers and `%s` ...
🌐
W3Schools
w3schools.com › c › c_variables_format.php
C Format Specifiers
C Reference C Keywords C <stdio.h> C <stdlib.h> C <string.h> C <math.h> C <ctype.h> C <time.h> C Examples C Real-Life Examples C Exercises C Quiz C Code Challenges C Practice Problems C Compiler C Syllabus C Study Plan C Interview Q&A · ❮ Previous Next ❯ · Format specifiers are used together with the printf() function to print variables.
🌐
Study.com
study.com › computer science courses › computer science 111: programming in c
Formatting Display Strings in C Programming - Lesson | Study.com
June 28, 2024 - When you make a call to C language's printf function, you have to provide a string of characters. This is called an escape sequence, or a backslash followed by a character telling the program to perform some nongraphical function. We also use format specifiers to include integers within strings.
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › c_standard_library › c_function_sprintf.htm
C Library - sprintf() function
The C Library sprintf() function allows you to create strings with specified formats, similar to printf(), but instead of printing to the standard output, it stores the resulting string in a character array provided by the user.
🌐
TutorialsPoint
tutorialspoint.com › cprogramming › c_format_specifiers.htm
Format Specifiers in C
Hence, a char variable with %c format specifier corresponds to the character in single quotes. On the other hand, if you use the %d specifier, then the char variable will be formatted to its ASCII value.
🌐
Wikipedia
en.wikipedia.org › wiki › Printf
printf - Wikipedia
2 weeks ago - Mismatch between the format specifiers and count and type of values results in undefined behavior, and the program might crash or vulnerabilities may arise. The format string is encoded as a template language consisting of verbatim text and format specifiers that each specify how to serialize ...
🌐
Udemy
blog.udemy.com › home › it & development › software development › c string format – a beginner’s guide
C String Format - A beginner's guide - Udemy Blog
April 14, 2026 - C string format refers to how C controls text output using format specifiers like `%s`, `%d`, and `%f` with functions like `printf()`. This article covers string basics, `printf()` syntax, and how to modify `%s` with field width, precision, ...
🌐
Unstop
unstop.com › home › blog › format specifiers in c — complete list with code examples (2026)
Format Specifiers in C — Complete List with Code Examples (2026)
May 19, 2026 - Format specifiers in C are placeholders used in printf() and scanf() to specify data types during input/output operations. The most commonly used format specifiers are: %d (integer), %f (float), %s (string), %c (character), %lf (double), and ...
🌐
Medium
medium.com › @mazen.elheni › format-specifiers-in-c-e93a9bbf46d0
Format Specifiers in C. In C programming, format specifiers are… | by Mazen Elheni | Medium
February 6, 2025 - We can use the %o format specifier in the C program to print or take input for the unsigned octal integer number. ... The %x format specifier is used in the formatted string for hexadecimal integers.
🌐
GNU
gnu.org › software › gettext › manual › html_node › c_002dformat.html
16.3.1 C Format Strings
ISO C 23 specifies system-independent format string elements, for example, "%w64d" instead of "%" PRId64; however, as of 2024, these are not implemented across systems and therefore cannot be used portably.
🌐
cppreference.com
en.cppreference.com › c › io › fprintf
printf, fprintf, sprintf, snprintf, printf_s, fprintf_s, sprintf_s, snprintf_s - cppreference.com
Strings: padding: [ Hello] [Hello ] [ Hello] truncating: Hell Hel Characters: A % Integers: Decimal: 1 2 000003 0 +4 -4 Hexadecimal: 5 a A 0x6 Octal: 12 012 04 Floating-point: Rounding: 1.500000 2 1.30000000000000004440892098500626 Padding: 01.50 1.50 1.50 Scientific: 1.500000E+00 1.500000e+00 Hexadecimal: 0x1.8p+0 0X1.8P+0 Special values: 0/0=-nan 1/0=inf Fixed-width types: Largest 32-bit value is 4294967295 or 0xffffffff
🌐
SEI CERT
wiki.sei.cmu.edu › confluence › display › c › FIO47-C.+Use+valid+format+strings
FIO47-C. Use valid format strings | CERT Secure Coding
The formatted output functions ( fprintf() and related functions) convert, format, and print their arguments under control of a format string. The C Standard, 7.23.6.1, paragraph 3 [ ISO/IEC 9899:2024 ], specifies
🌐
Algor Education
cards.algoreducation.com › en › content › ByB7z_bI › c-programming-string-formatting
String Formatting in C Programming | Algor Cards
String formatting in C programming is crucial for presenting data clearly. Learn about printf(), format specifiers like %c, %d, %f, and modifiers for precision and alignment. Mastering these tools ensures readable, consistent output and is vital for user-friendly applications.