Using sprintf without a manually allocated buffer

The application I'm working on uses the sprintf

logger to format the text that is written to the file. So something like:

char buffer[512];
sprintf(buffer, ... );

      

This sometimes causes problems when the message being sent becomes too large for the manually allocated buffer.

Is there a way to get the behavior sprintf

without having to manually allocate memory?

EDIT: while sprintf

is a C operation, I am looking for C ++ type solutions (if any!) For me to get this behavior ...

+7


source to share


5 answers


No, you cannot use sprintf()

enough memory to allocate. Alternatives include:



  • use snprintf()

    to truncate a message - doesn't completely solve your problem, but prevents a buffer overflow problem.
  • double (or triple or ...) buffer - unless you are in a restricted environment
  • use C ++ std::string

    and ostringstream

    - but you will lose printf format, you will need to use the <operator
  • use the Formatting Format that comes with a% operator like printf
+10


source


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



+18


source


I also don't know the version that avoids the allocation, but if the C99 sprintfs allows a NULL pointer as a string. Not very efficient, but it will give you a complete string (as long as there is enough memory available) without risking an overflow:

length = snprintf(NULL, ...);
str = malloc(length+1);
snprintf(str, ...);

      

+5


source


"the logger uses sprintf to format the text that is written to the file"

fprintf()

does not impose any size restrictions. If you can write text directly to a file, do it!

I assume there is an intermediate processing step. If you know how much space you need, you can use malloc()

to allocate that much space.

One technique like this is to allocate a buffer of a reasonable size (which will be big enough 99% of the time), and if it's not big enough, split the data into chunks that you process one by one.

+3


source


With vanilla version of sprintf, it is impossible to prevent overwriting data in the buffer. This is true regardless of whether the memory was allocated or manually allocated on the stack.

To prevent buffer overwriting you need to use one of the safer versions of sprintf, like sprintf_s (windows only)

http://msdn.microsoft.com/en-us/library/ybk95axf.aspx

+1


source







All Articles