Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sprintf without a manually allocated buffer

Tags:

c++

c

string

memory

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...

like image 778
jpoh Avatar asked Nov 17 '08 06:11

jpoh


2 Answers

You can use asprintf(3) (note: non-standard) which allocates the buffer for you so you don't need to pre-allocate it.

like image 196
Jason Coco Avatar answered Sep 21 '22 14:09

Jason Coco


No you can't use sprintf() to allocate enough memory. Alternatives include:

  • use snprintf() to truncate the message - does not fully resolve your problem, but prevent the buffer overflow issue
  • double (or triple or ...) the buffer - unless you're in a constrained environment
  • use C++ std::string and ostringstream - but you'll lose the printf format, you'll have to use the << operator
  • use Boost Format that comes with a printf-like % operator
like image 28
philant Avatar answered Sep 20 '22 14:09

philant