As i understand, author of the thread want to use sprintf() for formatting text. This function indeed very useful, the only one problem is that it is just gets the pointer and writes to it without worrying about buffer size (because it is do not know about the size of it).
So, if you want all the list of solutions i see, here it is:
1. write your own sprintf-like function with using stringc or stringw or any other "modern" type (which can handle sizes correctly == dynamically). -- If you can do that -- that would be the best way.
2. if you are writing for Microsoft Windows CE 5.0, you can use _snprintf() to format text. It takes all the same but also the maximum buffer -- just all that is necessary.
3. if you can use Microsoft specific dialect -- you can use function sprintf_s() -- it is secure version of sprintf(). It also receives the maximum buffer size value.
4. since you cannot easily check if you pre-allocated buffer will be enough, it is not-bad-but-ofcause-very-far-from-ideal practice to use very large buffer (like i wrote == 10000). This is the easiest way to solve the problem. The only thing is necessary to remember is use it every time where you completely sure about the length given into function. For example, i using same functions to do logging of actions in the application -- all calls of the function i do with completely known parameters, like "Initialization..." or "Detected video memory: %u Mb" -- shortly, i do not pass values to this function directly from User, and if i need to do so, i just do next:
Code: Select all
...
string userName; // string == some clever string-storage class, like stringc, stringw or CString, or std::string
ReadUserName(&userName);
if (userName.length() > 100)
{
ShowErrorToUser("To long name");
return false;
}
else
{
writeLog("User with name \"%s\" registered", userName); // this function internally based on sprintf() with critical buffer mass == 10000 :)
return true;
}
...
That is not some working code, but i hope that shows the aim.
SO,
all usages of unsafe sprintf() is just because of its format-abilities. If you do not need them -- do not use this function (you can always use strncpy() -- with it you can handle buffer overflow), BUT if you want formatting features -- write your own sprintf-like function or use very large buffer and hope and pray