-1

If I compile my code containing vsnprintf on VS2015 it complains about :

warning C4996: 'vsnprintf': This function or variable may be unsafe.  
               Consider using vsnprintf_s instead.

If i use vsnprintf_s then gcc fails compiling it.

How to solve this? I would like to compile the code without (suppressed) warnings and platform independent.

Using C++ streams is not possible because the va_list and format string is created in C-Code.

YSC
  • 38,212
  • 9
  • 96
  • 149
vlad_tepesch
  • 6,681
  • 1
  • 38
  • 80
  • Write your own implementation of vsnprintf? Alternatively, I think you should switch off the warning (you will get it from things like memcpy). – Martin Bonner supports Monica Jan 15 '18 at 14:38
  • 3
    This is just Microsoft warning you that you are being unfaithful and thinking about other platforms. Their opinion, not mine. – MSalters Jan 15 '18 at 14:40
  • @YSC it is in some kind of c wrapping code. so using streams is not a valid solution because the format string and varargs are from the c-world – vlad_tepesch Jan 15 '18 at 14:42
  • Note [Do you use the TR-24731 "safe" functions?](https://stackoverflow.com/questions/372980/do-you-use-the-tr-24731-safe-functions) – and in particular my answer which notes that the differences between `vsnprintf_s()` and `vsnprintf()` are significant. It also notes that in modern MS Visual Studio, `vsnprintf()` differs from `_vsnprintf()`. Much the simplest is to suppress the warnings from MS and use (standard) `vsnprintf()`. – Jonathan Leffler Jan 15 '18 at 15:07
  • I'd be happy to have feedback on my answer, dear OP. – YSC Jan 16 '18 at 10:28

1 Answers1

1

Well, write MS-specific code:

#ifndef _MSC_VER
#define vsnprintf_s(buf, size, count, format, list) std::vsnprintf(buf, size, format, list)
#endif // _MSC_VER

char buf[64];
vsnprintf_s(buf, sizeof(buf), _TRUNCATE, "%s...", valist);
YSC
  • 38,212
  • 9
  • 96
  • 149
  • doesn't even have to be a #define – peterchen Jan 15 '18 at 15:05
  • @peterchen I'm reluctant to define a C++ identifier named `vsnprintf_s` just in case there are distros defining it in their C++ implementation. But you're right. – YSC Jan 15 '18 at 15:07