🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →sprintf and snprintf Explained
Format numbers and text into a string buffer safely. Learn sprintf, snprintf, return values and truncation, then test yourself with a quiz and interview questions. Part of our free C programming course.
The sprintf and snprintf functions do what printf does, but instead of sending text to the screen they write it into a char array. That makes them the standard way to build log lines, UART messages, file names and display text in embedded C programming. This final lecture of the Strings section of our free C tutorial shows both functions with real compiled output, explains why sprintf is risky, and ends with a quiz and interview questions.
What You Will Learn
- How sprintf converts integers and floats into strings
- What the return value means
- Why snprintf is the safe choice
- How to detect truncated output
- How to build one long message piece by piece
- Quiz and interview questions on the whole lecture group
Prerequisites
You should know printf format specifiers (Input-Output chapter, cp3_2) and how a char array holds a null terminated string.
How sprintf Works
The declaration is int sprintf(char *buf, const char *format, ...);. Everything works as in printf, but the characters land in buf, and a terminating '\0' is added automatically. The function returns the number of characters written, not counting the terminator.
The danger of sprintf. It has no idea how big your buffer is. If the formatted text is longer than the array, it writes past the end. That is a buffer overflow. Use snprintf, which takes the buffer size and never writes more than that.
Complete Program: Format Into Buffers
Save as fmt_demo.c:
#include <stdio.h>
#include <string.h>
int main(void)
{
char buf[32];
int n;
int id = 1348;
float temp = 36.75f;
n = sprintf(buf, "%d", id);
printf("buf=\"%s\" returned=%d\n", buf, n);
n = snprintf(buf, sizeof buf, "T=%.2f C", temp);
printf("buf=\"%s\" returned=%d\n", buf, n);
/* truncation: snprintf reports what it WANTED to write */
char tiny[8];
n = snprintf(tiny, sizeof tiny, "voltage=%d mV", 3300);
printf("tiny=\"%s\" wanted=%d fits=%s\n", tiny, n,
(n < (int)sizeof tiny) ? "yes" : "no");
/* building one log line in pieces */
char line[64];
size_t off = 0;
const char *dev = "adc0";
unsigned raw = 0x0A5F;
off += snprintf(line + off, sizeof line - off, "[%s] ", dev);
off += snprintf(line + off, sizeof line - off, "ch%d ", 3);
off += snprintf(line + off, sizeof line - off, "raw=0x%04X (%u)", raw, raw);
printf("%s <- %zu chars\n", line, off);
return 0;
}
gcc -std=c11 -Wall -Wextra -pedantic -o fmt_demo fmt_demo.c
./fmt_demo
Compiling prints a -Wformat-truncation warning for the tiny line. That is expected: we deliberately wrote 15 characters into an 8 byte buffer to show truncation, and the compiler noticed. Output:
buf="1348" returned=4
buf="T=36.75 C" returned=9
tiny="voltage" wanted=15 fits=no
[adc0] ch3 raw=0x0A5F (2655) <- 28 chars
Reading the output
| Line | Explanation |
|---|---|
returned=4 | “1348” is 4 characters, the terminator is not counted |
%.2f gives 36.75 | Two digits after the decimal point; the float is promoted to double when passed |
tiny="voltage" | Only 7 characters fit, the 8th byte holds the terminator |
wanted=15 | snprintf returns how many characters it wanted to write, so a value of 8 or more means truncation |
28 chars | Each call returned its own length, and the running offset off tracked the total |
Building a Message in Pieces
The last part of the demo shows the pattern for assembling long messages. Keep an offset. After every call, add its return value to the offset and write the next piece at line + off with sizeof line - off bytes left. For production code, also check that off has not reached the buffer size, because after truncation off can exceed it and the next subtraction would wrap around. A safe habit is to stop when off >= sizeof line.
Converting Numbers to Strings
| Goal | Call |
|---|---|
| Integer to decimal text | snprintf(buf, sizeof buf, "%d", x) |
| Hexadecimal with padding | snprintf(buf, sizeof buf, "0x%04X", x) |
| Float with 2 decimals | snprintf(buf, sizeof buf, "%.2f", y) |
| Several values in one line | Combine specifiers in one format string |
Printing a float with plain %f shows six decimals and may reveal rounding noise from the float type, for example 82.333336 for a float average. Choose a precision such as %.2f to print what you need.
Embedded Considerations
- On small microcontrollers the C library’s float formatting is large. Some toolchains need a special linker option to enable
%f - The functions use stack space internally. Check stack depth in tasks with small stacks
- For tight interrupt code, avoid formatting there and send raw values to a lower priority task
Common Mistakes and Troubleshooting
- Buffer too small for sprintf. Overflow and stack corruption. Switch to snprintf.
- Using sizeof on a pointer parameter. Inside a function that received
char *buf,sizeof bufis the pointer size. Pass the length as a separate argument. - Mismatched specifier.
%dwith a float prints garbage. The compiler warns with-Wall. - Ignoring the return value. Without checking it you cannot tell whether the text was cut.
- Passing user input as the format string. Always write
snprintf(buf, n, "%s", input), neversnprintf(buf, n, input).
Best Practices
- Default to
snprintfand treatsprintfas legacy - Check that the return value is smaller than the buffer size
- Keep format strings as literals
- Choose explicit precision for floats
Summary and Key Takeaways
- sprintf and snprintf format into memory instead of the screen
- Both add the terminator and return the length without it
- snprintf limits the write and reports the wanted length for truncation checks
- Build long messages with a running offset
With this you have covered arrays of pointers to strings, dynamic strings, lookup tables, sorting and formatting. Now test yourself.
Quiz: Test Yourself
Click a question’s answer line to reveal it.
Multiple choice
- What is
sizeof(const char *p[6])on a 32-bit microcontroller where a pointer is 4 bytes?- A) 6
- B) 24
- C) 6 plus the string lengths
- D) 4
Answer
B. Six pointers of 4 bytes each.
- Which line fails to compile?
char a[3][8]; const char *p[3];- A)
p[0] = "x"; - B)
a[0] = "x"; - C)
strcpy(a[0], "x"); - D)
p[1] = p[0];
Answer
B. A row of a 2-D array is an array and cannot be assigned.
- A)
- How many bytes must you allocate to store the string
"hello"with malloc?- A) 5
- B) 6
- C) 4
- D) 10
Answer
B. Five characters plus the terminator.
- What does snprintf return?
- A) Number of bytes actually written including the terminator
- B) Number of characters that would have been written, without the terminator
- C) Always zero
- D) The buffer size
Answer
B. It is the length it wanted to produce, which is how you detect truncation.
- Which function compares the contents of two strings?
- A)
== - B)
strlen - C)
strcmp - D)
strcat
Answer
C. The operator == compares addresses.
- A)
- What does
static const char *const t[]protect?- A) Only the characters
- B) Only the pointers
- C) Both the characters and the pointers
- D) Neither
Answer
C. The first const covers the text, the second covers the pointers.
- For an array of char pointers, what type does a qsort comparator receive for each argument?
- A) char
- B) char *
- C) pointer to a char pointer, as void *
- D) int
Answer
C. qsort passes the address of each array element.
- Which standard removed the gets function?
- A) C89
- B) C99
- C) C11
- D) It still exists everywhere
Answer
C. Use fgets instead.
Predict the output
Question 1
char buf[16];
int n = snprintf(buf, sizeof buf, "%d-%d", 12, 345);
printf("%s %d\n", buf, n);
Answer
12-345 6The text is six characters, and it fits.
Question 2
char buf[4];
int n = snprintf(buf, sizeof buf, "abcdef");
printf("%s %d\n", buf, n);
Answer
abc 6Only three characters fit plus the terminator, but the return value is 6, the wanted length.
Question 3
const char *t[] = { "b", "a", "c" };
const char *x = t[0];
t[0] = t[2];
t[2] = x;
printf("%s%s%s\n", t[0], t[1], t[2]);
Answer
cabSlots 0 and 2 swapped their addresses, so the order is c, a, b.
Practice tasks
- Write a function that returns the name of a weekday from a number 0 to 6 using a lookup table with bounds checking.
- Read five words with fgets, store them with malloc, sort them, print them, and free them.
- Build the line
[uart1] baud=115200 okwith snprintf into a 40 byte buffer and print how many characters it has.
Interview Questions
1. What is the difference between char a[5][10] and char *a[5]?
The first owns 50 characters in one block. The second owns five pointers, and each must be pointed to valid memory before writing through it.
2. Why is strcpy into an unset pointer slot dangerous?
The slot holds an indeterminate address, so strcpy writes to arbitrary memory. This is undefined behaviour.
3. Why allocate strlen plus one?
strlen excludes the terminator, but the stored string must include it.
4. Why should gets never be used?
It cannot bound the input and was removed in C11. Use fgets with the buffer size.
5. Why is sorting an array of pointers faster than sorting a 2-D char array?
Swapping pointers moves a few bytes, while swapping rows copies the entire fixed width of each row.
6. How do you detect truncation with snprintf?
Compare the return value with the buffer size. If it is greater than or equal to the size, the output was cut.
7. What is wrong with snprintf(buf, n, user_text)?
If the text contains percent signs they are treated as format specifiers. Use a literal “%s” format instead.
8. How would you keep a message table out of RAM?
Declare it static const char *const so the linker can place pointers and text in flash.
9. Why must a qsort comparator for strings dereference its arguments?
Because qsort passes addresses of the array elements, and each element is itself a pointer to the string.
10. What happens if you modify a string literal?
It is undefined behaviour. On many systems the literal sits in read-only memory and the program faults.
11. Why free each string and then set the pointer to NULL?
Freeing releases the block. Setting NULL prevents use after free and makes a second free harmless.
12. When would you prefer a 2-D char array over a pointer array?
When the text must be edited in place and a maximum length is known, or when the project forbids dynamic allocation.
Frequently Asked Questions
What is the difference between sprintf and snprintf?
snprintf takes the buffer size and never writes beyond it. sprintf does not.
Does sprintf add the null terminator?
Yes, but the buffer must have room for it.
Why does snprintf return a larger number than the buffer?
It returns the length it wanted to write, so you can tell the text was truncated.
Can I use sprintf to convert an int to a string in embedded C?
Yes, but prefer snprintf with the buffer size and consider the code size cost of the library.
Is this part of a free embedded systems course?
Yes. Formatting text into buffers appears in almost all firmware logging code, and this lecture belongs to our free embedded C course.
Where should I go next?
Continue to the next chapter of the free C programming course.
Finish the Free C Programming Course
You have completed this part of the free embedded C course. Review the quiz, then move on to the next chapter.

2 Comments