Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is sscanf considered safe to use?

I have vague memories of suggestions that sscanf was bad. I know it won't overflow buffers if I use the field width specifier, so is my memory just playing tricks with me?

like image 488
nmichaels Avatar asked May 03 '11 17:05

nmichaels


People also ask

What can I use instead of sscanf?

If you really want not to use streams (It's good because of readability), you can use StringPrintf. Nice bit of code (I'm using something almost the same already), though it's a replacement for printf rather than sscanf .

What happens if sscanf fails?

sscanf() Return value If successful, the sscanf() function returns the number of receiving arguments successfully assigned. If a matching failure occurs before the first receiving argument was assigned, returns zero.

Does sscanf change the string?

sscanf never modifies the string you pass to it; you can tell by the const qualifier.

What does the sscanf function do?

Description. The sscanf() function reads data from buffer into the locations that are given by argument-list. Each argument must be a pointer to a variable with a type that corresponds to a type specifier in the format-string.


2 Answers

I think it depends on how you're using it: If you're scanning for something like int, it's fine. If you're scanning for a string, it's not (unless there was a width field I'm forgetting?).


Edit:

It's not always safe for scanning strings.

If your buffer size is a constant, then you can certainly specify it as something like %20s. But if it's not a constant, you need to specify it in the format string, and you'd need to do:

char format[80]; //Make sure this is big enough... kinda painful
sprintf(format, "%%%ds", cchBuffer - 1); //Don't miss the percent signs and - 1!
sscanf(format, input); //Good luck

which is possible but very easy to get wrong, like I did in my previous edit (forgot to take care of the null-terminator). You might even overflow the format string buffer.

like image 64
user541686 Avatar answered Oct 05 '22 23:10

user541686


The reason why sscanf might be considered bad is because it doesnt require you to specify maximum string width for string arguments, which could result in overflows if the input read from the source string is longer. so the precise answer is: it is safe if you specify widths properly in the format string otherwise not.

like image 41
z33m Avatar answered Oct 05 '22 23:10

z33m