In the application that I am working on, the logging facility makes use of sprintf to format the text that gets written to file. So, something like:
char buffer[512]; sprintf(buffer, ... );
This sometimes causes problems when the message that gets sent in becomes too big for the manually allocated buffer.
Is there a way to get sprintf behaviour without having to manually allocate memory like this?
EDIT: while sprintf is a C operation, I’m looking for C++ type solutions (if there are any!) for me to get this sort of behaviour…
No you can’t use
sprintf()to allocate enough memory. Alternatives include:snprintf()to truncate the message – does not fully resolve your problem, but prevent the buffer overflow issuestd::stringandostringstream– but you’ll lose the printf format, you’ll have to use the << operator