And should the non-standard snprintf always be used?
And should the non-standard snprintf always be used?
Is sprintf unsafe? Yes, it can be. It is if you don't supply a large enough buffer to hold the data you format.
I always recommend the use of safer more non-portable functions due to security issues.
But you should at least write a wrapper for the non-standard function and wrap it around the standard function to make it compile it compilers that does not support the function.
sprintf() is unsafe if you do not KNOW that the size of the input is safe. For example, if you are printing strings that you know from other places are no longer than 99 chars into a 120 char array, where the formatting itself adds no more than 20 characters then you are safe.
The difficulty, of course, is to judge whether the format and input is within range or not. You may for example want to format a floating point value, and you expect it to fit in %6.6f, but for some reason the value is greater than 999999, so the resulting string is longer than the format expects [and bear in mind that negative numbers take up one extra space, so a negative, large enough, number would also produce the same type of problem].
sprintf certainly has the ability to overflow.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
Almost anything can be unsafe if you don't use it properly.