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?
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 .
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.
sscanf never modifies the string you pass to it; you can tell by the const qualifier.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With