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...
You can use asprintf(3) (note: non-standard) which allocates the buffer for you so you don't need to pre-allocate it.
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::string
and ostringstream
- but you'll lose the printf format, you'll have to use the << operatorIf 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