Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 5578
  • Last Modified:

_snprintf() -> _snprintf_s()


Has anyone had experience using:


I was using _snprintf() before but now visual studio 2005 says to use _snprintf_s() instead. What headers must I include? I just have a standard win32 console project.

4 Solutions
Dariusz DziaraProgrammerCommented:
As far as I know _snprintf_s() has just better buffer overflow control.
Locate in MSDN description of the function and you will see there what you need to include.

Dariusz DziaraProgrammerCommented:
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

See http://msdn2.microsoft.com/en-us/library/f30dzcf6(VS.80).aspx ("_snprintf_s, _snprintf_s_l, _snwprintf_s, _snwprintf_s_l ") as well as http://msdn2.microsoft.com/en-us/library/8ef0s5kh.aspx  ("Security Enhancements in the CRT") about the difference. You still can use the 'old' versions by placing a


in your code or disabling the warning. NOTE that '_snprintf_s()' isn't compatzible with other compilers.
If Microsoft support strtod and strtol I would use them directly instead of parsing out % directives in a string which is neither fast nor typesafe. For example:

int x;
sprintf(s, "%ld", x);

is a runtime error.

char* buffer = ... // point to whatever you want and...
char* p = buffer;
strtod(x, p); // print x into the buffer

The state of the art of C++ streams is surprisingly bad, and you can get massive speed improvements from writing your own stream; it's really too bad some library doesn't provide a nice one.
If compiiler knows buffer length, you can replace sprint with sprintf_s and this will compile:

char s[100];
sprintf(s, ...);
replace with:
sprintf_s(s, ...);  // works with same parameters as printf

There is macro which converts such call to valid sprintf_s call.
If compiler doesn't know buffer size, you must supply additional parameter.

Just replace and sprintf with sprintf_s and most of them will compile. In lines which are not compiled, add size_t sizeOfBuffer parameter. Notice that sizeOfBuffer must be equal or less then actual buffer size. If sizeOfBuffer is more than actual buffer size, program will crash.

void DoSomething(char* s)
    sprintf_s(s, bufferSize, ...);   // here you must add buffer size because compiler doesn't know it

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now