3

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?

2
  • 1
    There are template versions that can deduce the size if it is possible from the buffer parameter. 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/… Commented Jul 9, 2021 at 7:55
  • If you are using 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 of char as the first argument, where the size is a template parameter. The latter cannot be passed a char * (since the size cannot be deduced). Commented Jul 9, 2021 at 7:59

1 Answer 1

5

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.