Visual Studio prompts me to replace sprintf with sprintf_s, instead of snprintf.
sprintf_s does not require a length parameter, how does it avoid buffer overflow issue?
There are 2 versions. One template version which tries to deduce the size of the buffer and one where you pass the size.
int sprintf_s<_Size>(char (&_Dest)[_Size], const char *_Format, ...)
int sprintf_s(char * _DestBuf, size_t _SizeInBytes, const char *_Format, ...)
If the first one cannot be deduced, you will have to pass the size yourself
So this:
char buf[100];
sprintf_s(buf, "%d", 1);
Will instantiate a function template
sprintf_s<100>();
This will generate a compiler error:
char *buf = new char[100];
sprintf_s(buf, "%", 1);
And you have to use the other version to make it compile:
sprintf_s(buf, 100, "%d", 1);
bufferparameter. If that fails you need to provide the size. learn.microsoft.com/en-us/cpp/c-runtime-library/reference/… This has an example to show when it will deduce the size and when it will not. learn.microsoft.com/en-us/cpp/c-runtime-library/…sprintf_s()that was introduced in C11, the second argument is the size of the string buffer. Microsoft also specify a non-standard templated version in C++, which accepts an array ofcharas the first argument, where the size is a template parameter. The latter cannot be passed achar *(since the size cannot be deduced).