2

I need variant of snprint that has guarantee that it never calls malloc.
That's because this snprintf (let's call it safe_snprint()) is going to
be called from places where malloc will fail or deadlock.

What is closer to truth, 1 or 2 ?

  1. On Windows, native snprintf might call malloc. Then
    i need to pull opensource snprintf.c and call it safe_snprintf(). Or

  2. On Windows native snprint is guaranteed to never call malloc.

I'd prefer (2) if it is documented somewhere. Thanks

Andrei
  • 8,606
  • 10
  • 35
  • 43
  • I don't have the MSVC sources in front of me at the moment, but there is _no_ reason why `snprintf` would need to do any allocations, ever. Everything that needs to be done can happen using only stack-based memory. – C. K. Young Jul 23 '11 at 22:57

3 Answers3

4

The implementation of _snprintf() in the VC libs (MSVCRT) will only call malloc on floating point conversions if and only if (iff) the format precision exceeds 163 characters. This applies to %E %G %A %e %f %g and %a format specifiers.

This should apply to all releases of MSVCRT since at least version 6.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
1

I cannot find documentation according to windows snprintf implementation but this link states that there could be reason to inner malloc call. Also I do not think so that any standard forbids developers to use it. So I recommend you to use the first approach. Here you could find a list of snprintf implementations.

eugene_che
  • 1,997
  • 12
  • 12
0

There is no reason why snprintf() should ever call malloc(). Period.

But, however, you cannot be sure without viewing the source. And even then you cannot be sure that it will stay this way.

If you have to be absolutely sure, than you might want to implement your own snprintf().

ckruse
  • 9,642
  • 1
  • 25
  • 25
  • snprintf() works on pre-allocated memory. It does not need its own memory. I actually cannot imagine why it would call malloc() at all. But why don't you just do a trace? int main(void) { char buff[512]; snprintf(buff,512,"%d %s", 10, "lala"); } and a trace programm can show you the truth. – ckruse Jul 23 '11 at 23:05
  • This covers only one specific, and small & simple, format specifier. What if user prints 120k long string ? What if call uses %$ specifiers ? What is user uses %*.* specifiers ? One needs access to the source to be sure. – Andrei Jul 24 '11 at 18:20