c / intermediate
Snippet
Safe String Formatting with snprintf
The snprintf function is a safer alternative to sprintf because it requires a maximum buffer size. This prevents buffer overflows by ensuring that no more than 'n' characters are written, including the null terminator. If the output is truncated, the return value indicates the total number of characters that would have been written.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>int main() {char buffer[16];int value = 123456;// Prevents buffer overflow by specifying the sizeint written = snprintf(buffer, sizeof(buffer), "Val: %d", value);if (written >= (int)sizeof(buffer)) {printf("Output truncated! Need %d bytes.\n", written + 1);}printf("Result: %s\n", buffer);return 0;}
Breakdown
1
char buffer[16];
Allocates a small fixed-size character array.
2
snprintf(buffer, sizeof(buffer), "Val: %d", value);
Writes the formatted string while respecting the buffer size limit.
3
if (written >= (int)sizeof(buffer))
Checks if the return value is greater than or equal to the size, indicating truncation.