swprintf_s causing Random Crashes and Stack Corruption

This is what happens if you don’t read documentation properly Smile

swprintf_s [https://msdn.microsoft.com/en-us/library/ce3zzk1k.aspx ]

int swprintf_s(
   wchar_t *buffer,
   size_t sizeOfBuffer,
   const wchar_t *format,

Maximum number of characters to store.

Documentation says the argument is the number of characters to store and not the size of buffer. More often, such APIs asks for the size of buffer and even in this case would work fine if it were not wide character string where each character takes two bytes, vs. 1 byte in normal string.

swprintf_s ( buff, sizeof(buff), L”string to %s “, “format” );

this will end up corrupting stack variables. You may crash for various reasons, all manifestations of this corruption. The right way would be to read the documentations Smile

swprintf_s  (buff, sizeof(buff)/sizeof(wchar_t), L”string to %s”, L”format”);

Hope this help!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s