I have snprintf
and it can avoid a buffer overflow, but why there is no function called snscanf
?
Code:
int main()
{
ch
a little more wrinkles. the 'n' usually refers to the first argument in the snprintf. Now, it is true that the first string argument in sscanf is not written to. However, it is read. Thus, the following could segfault:
char s[2];
s[0]='1'; s[1]='3';
int x;
sscanf(s, "%d", &x);
because stepping one char beyond s could inadvertently step into reading from undefined memory (or continue the integer from another variable). so, something like this would be useful:
snscanf(s, 2, "%d", &x);
s is not a string, of course, but it is a character array. the 'n' in the snscanf would prevent overstepping (reading from) the first (source string) argument, and not be related to the destination argument.
the way to avoid this is to first make sure that s is terminated by a '\0' within 2 characters. you can't use strlen, of course. you need strnlen, and a test whether it is less than 2. if it is 2, then more copying effort is needed first.