A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
sprintf is printf that writes to a char buffer instead of stdout. It formats integers, floats, strings, and pointers into a text representation and stores the result in memory. It is how you build log messages, construct filenames, serialize values to text, and prepare data for network protocols. It is also how you overflow buffers, because sprintf does not take a size parameter. snprintf does. Use snprintf.
#include <stdio.h>#include <string.h>int main(void) {char buffer[128];int user_id = 42;const char *role = "admin";double score = 97.5;sprintf(buffer, "User #%d (%s) scored %.1f%%", user_id, role, score);printf("Formatted: %s\n", buffer);printf("Length: %zu\n", strlen(buffer));return 0;}
#include <stdio.h>int main(void) {char small[16];sprintf(small, "This string is definitely longer than sixteen bytes");printf("Result: %s\n", small);return 0;}
52 bytes written into a 16-byte buffer. sprintf does not know the buffer size. It writes until the format is exhausted. The overflow corrupts the stack. ASan catches it. Without ASan, this is a silent stack smash that might overwrite the return address and become exploitable.
#include <stdio.h>int main(void) {char buffer[16];int written = snprintf(buffer, sizeof(buffer), "Hello, %s! You have %d messages.", "Alex", 42);printf("Buffer: \"%s\"\n", buffer);printf("Would have written: %d chars\n", written);printf("Truncated: %s\n", (written >= (int)sizeof(buffer)) ? "yes" : "no");return 0;}
snprintf writes at most sizeof(buffer) - 1 characters plus a null terminator. The return value is the number of characters that would have been written if the buffer were large enough. If that value is greater than or equal to the buffer size, truncation occurred. This gives you detection and recovery. sprintf gives you neither.
sprintf is legacy. snprintf is the replacement. The only reason to use sprintf is when you have mathematically proven the output fits, such as formatting a single int into a 32-byte buffer. Even then, snprintf costs nothing extra and gives you truncation detection. Use it by default. Next: char arrays vs pointers to string literals, a distinction that determines whether your code crashes on write.
Finish the lesson once you have worked through the material. This awards ★ 30 XP.