0
0
CHow-ToBeginner · 3 min read

How to Use sprintf and snprintf in C: Syntax and Examples

In C, sprintf formats data into a string buffer without size checking, which can cause buffer overflow. snprintf is safer because it limits the number of characters written, preventing overflow by specifying the buffer size.
📐

Syntax

sprintf writes formatted data to a string buffer without checking buffer size.
snprintf writes formatted data to a string buffer but limits the number of characters to avoid overflow.

  • char *str: destination buffer
  • size_t size: max number of characters to write (for snprintf)
  • format: format string like in printf
  • Additional arguments: values to format
c
int sprintf(char *str, const char *format, ...);
int snprintf(char *str, size_t size, const char *format, ...);
💻

Example

This example shows how to use sprintf and snprintf to format an integer and a string into a buffer safely.

c
#include <stdio.h>

int main() {
    char buffer1[50];
    char buffer2[10];
    int age = 25;
    const char *name = "Alice";

    // Using sprintf (no size limit)
    sprintf(buffer1, "Name: %s, Age: %d", name, age);
    printf("sprintf output: %s\n", buffer1);

    // Using snprintf (with size limit)
    int written = snprintf(buffer2, sizeof(buffer2), "Name: %s", name);
    printf("snprintf output: %s\n", buffer2);
    printf("Characters written (excluding null): %d\n", written);

    return 0;
}
Output
sprintf output: Name: Alice, Age: 25 snprintf output: Name: Ali Characters written (excluding null): 10
⚠️

Common Pitfalls

Using sprintf without checking buffer size can cause buffer overflow, leading to crashes or security issues.
snprintf helps prevent this by limiting output size, but you must check its return value to detect truncation.

Also, remember snprintf returns the number of characters that would have been written if enough space was available, so if this is >= buffer size, output was cut off.

c
#include <stdio.h>

int main() {
    char smallBuffer[5];

    // Unsafe: may overflow
    // sprintf(smallBuffer, "Hello World"); // Dangerous!

    // Safe: limits output to buffer size
    int ret = snprintf(smallBuffer, sizeof(smallBuffer), "Hello World");
    if (ret >= sizeof(smallBuffer)) {
        printf("Output was truncated!\n");
    }
    printf("Buffer content: %s\n", smallBuffer);

    return 0;
}
Output
Output was truncated! Buffer content: Hell
📊

Quick Reference

FunctionPurposeKey Point
sprintfFormat data into string bufferNo buffer size check, risk of overflow
snprintfFormat data into string buffer with size limitPrevents overflow, returns needed size
Return valueNumber of characters written or neededCheck to detect truncation with snprintf

Key Takeaways

Use snprintf instead of sprintf to avoid buffer overflow by specifying buffer size.
Always check snprintf's return value to detect if output was truncated.
sprintf does not limit output size and can cause security issues if buffer is too small.
snprintf returns the total length it would have written, allowing buffer size management.
Format strings in both functions work like printf, supporting placeholders like %d and %s.