CFunctionsIntermediate

snprintf()

Formats text into a buffer with size limits to prevent overflow.

Review the syntaxStudy the examplesOpen the coding app
int snprintf(char *buffer, size_t size, const char *format, ...);

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

Formats text into a buffer with size limits to prevent overflow.

snprintf is a variadic function designed for secure formatted output to a character buffer. Unlike its predecessor sprintf, snprintf introduces a 'size' parameter that specifies the maximum number of bytes to be written, including the null terminator. This is a critical security feature that prevents buffer overflow vulnerabilities. The function returns the total number of characters that would have been written if the buffer were large enough (excluding the null terminator). If the return value is greater than or equal to the size argument, truncation has occurred. From a performance perspective, calling snprintf with a size of 0 and a NULL buffer allows a developer to calculate the exact amount of memory needed before allocating a buffer, which is useful for dynamic string construction. However, excessive calls can lead to performance overhead due to the double-parsing of the format string.

Quick reference

Syntax

int snprintf(char *buffer, size_t size, const char *format, ...);

Inputs

Parameters

bufferchar* · Destination buffer.
sizesize_t · Total buffer capacity in bytes.
formatconst char* · Format string with specifiers.
... (optional)variadic · Values to format.

See it in practice

Examples

1

Basic Safe Formatting

#include <stdio.h>

int main() {
    char buffer[10];
    const char *name = "Alexander";
    snprintf(buffer, sizeof(buffer), "Hi %s", name);
    printf("Buffer: %s\n", buffer);
    return 0;
}
Output:
Buffer: Hi Alexan

Demonstrates how snprintf prevents overflow by truncating the input string to fit the 10-byte buffer (9 characters + null terminator).

2

Truncation Detection

#include <stdio.h>

int main() {
    char buffer[12];
    int len = snprintf(buffer, sizeof(buffer), "Status: %s", "Incomplete");
    if (len >= sizeof(buffer)) {
        printf("Output truncated! Needed %d chars, had %zu.\n", len, sizeof(buffer));
    }
    return 0;
}
Output:
Output truncated! Needed 19 chars, had 12.

Shows how to use the return value to detect if the entire string was successfully written to the buffer.

3

Dynamic Buffer Allocation

#include <stdio.h>
#include <stdlib.h>

int main() {
    const char *fmt = "Score: %d out of %d";
    int s1 = 95, s2 = 100;
    int size = snprintf(NULL, 0, fmt, s1, s2);
    char *dyn_buf = malloc(size + 1);
    snprintf(dyn_buf, size + 1, fmt, s1, s2);
    printf("%s\n", dyn_buf);
    free(dyn_buf);
    return 0;
}
Output:
Score: 95 out of 100

Uses a dry-run (size 0) to determine the exact memory required for the formatted string, followed by allocation.

Debug faster

Common Errors

1

LogicError

Cause: Assuming the return value represents the number of bytes actually written to the buffer.

Fix: Always remember that the return value is the number of characters that *would* have been written, not including the null terminator.

int written = snprintf(buf, 5, "123456"); // written is 6, but only 4 chars + \0 are in buf
2

BufferError

Cause: Off-by-one error by not providing enough space for the null terminator manually or using incorrect size.

Fix: Ensure the size parameter matches the total allocated size of the array, as snprintf handles the -1 internally for the null terminator.

char buf[5]; snprintf(buf, 4, "Hello"); // Buffer becomes 'Hel\0', ignoring the 5th byte available.

Runtime support

Compatibility

C99+

stdio.h; widely available on modern compilers

Source: MDN Web Docs

Common questions

Frequently Asked Questions

Formats text into a buffer with size limits to prevent overflow.

buffer: Destination buffer. size: Total buffer capacity in bytes. format: Format string with specifiers. ...: Values to format.

LogicError: Always remember that the return value is the number of characters that *would* have been written, not including the null terminator. BufferError: Ensure the size parameter matches the total allocated size of the array, as snprintf handles the -1 internally for the null terminator.