sprintf and snprintf in C: solved exercise

sprintf and snprintf in C: solved exercise

If you searched for a solved sprintf and snprintf exercise in C, here are the most common patterns: formatting numbers into strings, dynamically building file paths, and combining fields into a single buffer — with the key difference between sprintf (unbounded) and snprintf (safe, bounded).

snprintf is the safe version that never writes more than n bytes including the \0 terminator. In modern C code, snprintf is always preferred over sprintf.

Problem statement

  1. Use sprintf to build the string "Result: 42 (0x2A)".
  2. Use snprintf to build file paths with the pattern "/logs/day_03.log".
  3. Detect truncation when the buffer is too small.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <stdio.h>
#include <string.h>

int main(void) {
    char buf[64];

    /* 1. sprintf: decimal and hexadecimal number */
    sprintf(buf, "Result: %d (0x%X)", 42, 42);
    printf("%s\n", buf);

    /* 2. snprintf: safely build file paths */
    for (int day = 1; day <= 3; day++) {
        snprintf(buf, sizeof(buf), "/logs/day_%02d.log", day);
        printf("Path: %s\n", buf);
    }

    /* 3. Detect truncation */
    char small[10];
    int written = snprintf(small, sizeof(small), "Very long string: %d", 12345);
    if (written >= (int)sizeof(small)) {
        printf("Truncated: needed %d bytes, buffer is %zu\n",
               written, sizeof(small));
    }
    printf("Buffer: \"%s\"\n", small);

    return 0;
}

Expected output

1
2
3
4
5
6
Result: 42 (0x2A)
Path: /logs/day_01.log
Path: /logs/day_02.log
Path: /logs/day_03.log
Truncated: needed 22 bytes, buffer is 10
Buffer: "Very long"

Common mistakes

  • Using sprintf with fixed-size buffers: if the formatted text exceeds the buffer size, sprintf produces a buffer overflow (undefined behavior and a security vulnerability).
  • Not checking the return value of snprintf: it returns the number of bytes that would have been written without the limit; if >= n, truncation occurred.
  • Confusing snprintf with strncpy: snprintf always null-terminates; strncpy does not guarantee null-termination when the source is longer than n.
  • Forgetting the \0 in size calculations: snprintf(buf, 10, ...) leaves room for 9 characters plus the terminator.

Practical use

snprintf is the standard function for building formatted strings in C: file names, log messages, plain-text HTTP responses, and any scenario that combines numeric data and text. It is the safe alternative to manual concatenation with strcat.

Guided practice and full book

If you want a complete path with progressive difficulty:

FAQ

What exactly does snprintf return?

It returns the number of bytes that would have been written if the buffer were large enough, not counting the final \0. If the return value is >= n (the buffer size), the string was truncated and you need a larger buffer or truncation handling.

Why is sprintf considered unsafe?

Because it has no write limit. If the formatted text exceeds the buffer size, sprintf writes beyond the boundary, corrupting adjacent memory. This is a buffer overflow — in network code or with external input, it is an exploitable security vulnerability.

Is there a more modern alternative?

C11 introduced sprintf_s and snprintf_s (optional Annex K extensions), but adoption is limited. The standard practice is to always use snprintf with sizeof(buffer).