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
- Use
sprintfto build the string"Result: 42 (0x2A)". - Use
snprintfto build file paths with the pattern"/logs/day_03.log". - Detect truncation when the buffer is too small.
C solution
Expected output
Common mistakes
- Using
sprintfwith fixed-size buffers: if the formatted text exceeds the buffer size,sprintfproduces 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
snprintfwithstrncpy:snprintfalways null-terminates;strncpydoes not guarantee null-termination when the source is longer thann. - Forgetting the
\0in 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.
Recommended next exercise
- strcat and strncat in C: solved exercise
- strcpy and strncpy in C: solved exercise
- strlen, strchr, strstr in C: solved exercise
- All C exercises
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).