#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
#define NC 10
#define ALONGSTRING "A long string of nonsense that would've been truncated."
size_t len;
char *string = calloc(NC, sizeof(*string));
len = snprintf(string, NC, ALONGSTRING);
printf("Truncated string: '%s'\n", string);
if(len >= NC) {
string = realloc(string, (len + 1) * sizeof(*string));
snprintf(string, len + 1, ALONGSTRING);
}
printf("Non-truncated string: '%s'\n", string);
free(string);
return 0;
}
Friday, January 2, 2009
Preventing string truncation with snprintf()
One issue with using snprintf() (the buffer-overrun-preventing version of sprintf()) is that since the size of the char[] we're trying to "print" into is limited, truncation would occur if the string is longer than the char[] size. Yet after studying the manual carefully, I noticed that snprintf() actually returns the length of the resultant string, regardless of the size of the buffer. Below is a simple demonstration of how to prevent truncation with this feature and dynamical allocation of the character buffer.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment